使用for循环在R中使用ggplot创建多个图形
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,依此类推。所需的输出应类似于:
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 熔化也不是一个选项,因为我想为每个标准创建不同的图表。
有什么建议吗?
这为每个“标准”绘制了一个图
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
我有看起来与此类似的数据:
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 熔化也不是一个选项,因为我想为每个标准创建不同的图表。
有什么建议吗?
这为每个“标准”绘制了一个图
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