![](/img/trans.png)
[英]Using for loop on multiple columns to create title in r ggplot graphs
[英]Using for loop to create multiple graphs with ggplot in R
我有看起来与此类似的数据:
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,依此类推。 所需的 output 应该类似于:
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 熔化也不是一个选项,因为我想为每个标准创建不同的图表。
有什么建议么?
这为每个“标准”创建了一个 plot
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 package (v2.0.1) 创建于 2022-02-11
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.