本文介绍一下R语言的批量作图操作。
# Load libraries
library(tidyverse)
本人以iris数据集为例。
## # A tibble: 9 x 5
## # Groups: Species [3]
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## <dbl> <dbl> <dbl> <dbl> <fct>
## 1 5.4 3.4 1.5 0.4 setosa
## 2 5.2 3.5 1.5 0.2 setosa
## 3 5.1 3.8 1.6 0.2 setosa
## 4 5.8 2.7 3.9 1.2 versicolor
## 5 5.7 2.8 4.5 1.3 versicolor
## 6 5.6 3 4.5 1.5 versicolor
## 7 6.3 2.9 5.6 1.8 virginica
## 8 6.9 3.2 5.7 2.3 virginica
## 9 6.7 3.1 5.6 2.4 virginica
iris %>%
dplyr::group_split(Species) %>%
map(
# .x 或 . 是指以分组变量为分组的子集
~ ggplot(data = .x, aes(x = Sepal.Length, fill = Species)) +
geom_density() +
ggtitle(.x$Species))
## [[1]]
##
## [[2]]
##
## [[3]]
iris %>%
mutate(Species = as.character(Species))%>%
dplyr::group_by(Species) %>%
dplyr::group_map(
~ ggplot(data = .x, aes(x = Sepal.Length)) +
geom_density() +
## .y 指分组变量的值,必须为字符型,因子型结果因子水平数字。
ggtitle(.y))
## [[1]]
##
## [[2]]
##
## [[3]]
iris %>%
mutate(Species = as.character(Species)) %>%
dplyr::group_by(Species) %>%
dplyr::group_walk( ## 也可以group_map
~ ggsave(
paste0(.y, ".png"),
ggplot(data = .x, aes(x = Sepal.Length)) + # .x 或 . 是指以分组变量为分组的子集
geom_density() +
ggtitle(.y), ## .y 指分组变量的分组关键词
device = "png",
path = getwd()
)
)