我有類似這樣的資料:
Criteria Person A Person B Person C Person D
A 10 15 12 11
B 50 55 40 37
C 10 2 5 3
D 15 18 22 30
E 40 25 18 32
F 12 35 10 12
我需要為每個條件創建一個 ggplot 柱形圖,但我想使用 for 回圈來提高效率(或任何其他策略)。一張圖表示標準 A,一張圖表示 B,以此類推。所需的輸出應該類似于:
ggplot(aes(x = person, y = n)) geom_col() #for the criteria A
ggplot(aes(x = person, y = n)) geom_col() #for the criteria B
ggplot(aes(x = person, y = n)) geom_col() #for the criteria C
(...)
其中 x 是人 A、B、C 和 D,n 是計數 (10, 15, 12...)。這個想法是為每個標準自動創建一個圖表,而無需使用 filter() 手動創建和調整它們。
我找到了一些使用 facet_wrap 的選項,但這并不是我想要的。在這種情況下,從 reshape2 融化也不是一個選項,因為我想為每個標準創建不同的圖表。
有什么建議?
uj5u.com熱心網友回復:
這為每個“標準”繪制了一個圖
library(tidyverse)
sample_df <- data.frame(
stringsAsFactors = FALSE,
check.names = FALSE,
Criteria = c("A", "B", "C", "D", "E", "F"),
`Person A` = c(10L, 50L, 10L, 15L, 40L, 12L),
`Person B` = c(15L, 55L, 2L, 18L, 25L, 35L),
`Person C` = c(12L, 40L, 5L, 22L, 18L, 10L),
`Person D` = c(11L, 37L, 3L, 30L, 32L, 12L)
)
sample_df %>%
pivot_longer(cols = -Criteria,
names_to = "person",
names_prefix = "Person\\s",
values_to = "n") %>%
group_nest(Criteria) %>%
mutate(plot = map(data, ~ggplot(.x, aes(x = person, y = n)) geom_col())) %>%
pull(plot)
#> [[1]]

#>
#> [[2]]

#>
#> [[3]]

#>
#> [[4]]

#>
#> [[5]]

#>
#> [[6]]

由reprex 包于 2022-02-11 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/424480.html
