问题描述
所以我想为每个地方同时绘制多个图,y 轴为 Num of Visits,x 轴为 Day,但我不确定是否有函数可以做到这一点?
So I want to plot multiple plots at the same time for each place with Num of Visits on y-axis and Day on x-axis but I'm not sure if there is a function to do this?
所以我能够通过对地点 A 进行子集化来为地点 A 绘制一个情节:
So I was able to make a plot for place A by subsetting place A :
placeA <- subset(df$place=="A")
ggplot(data=placeA, aes(x=Day, y=Num_OfVisits, group=1)) +
geom_line(color="#00AFBB", size=0.5) +
theme(axis.text.x=element_text(angle=90,hjust=1, size=5))
但现在我想为其他地方生成一个图,我希望我可以一次性完成所有工作,因为我的数据集上有大约 1000 个地方,子集化需要一些时间.任何帮助将不胜感激.谢谢!
But now I want to generate a plot for the other places and I am hoping that I could do it all in one shot because there are around 1000 places on my dataset and subsetting is taking some time. Any help will be appreciated. Thank you!
推荐答案
您可以编写一个函数,将数据框和 Place
作为输入,然后循环遍历 Place 列以创建相应的图.
You can write a function that takes the data frame and
Place
as inputs then loop through all the values in Place
column to create the corresponding plots.
library(tidyverse)
df <- data_frame(
Place = c(rep(c("A", "B", "C"), each = 3)),
Num_of_Visits = seq(1:9),
Day = rep(c("Sunday", "Monday", "Tuesday"), 3)
)
df <- df %>%
mutate(Day = factor(Day, levels = c("Sunday", "Monday", "Tuesday")))
my_plot <- function(df, myvar) {
ggplot(data = df %>% filter(Place == myvar),
aes(x = Day, y = Num_of_Visits, group = 1)) +
geom_line(color = "#00AFBB", size = 0.5) +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
}
# test
my_plot(df, 'A')
循环遍历
Place
var,创建绘图&使用 purrr::map()
Loop through
Place
var, create plots & store them in a list using purrr::map()
plot_list <- unique(df$Place) %>%
purrr::set_names() %>%
purrr::map( ~ my_plot(df, .x))
str(plot_list, max.level = 1)
#> List of 3
#> $ A:List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ B:List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
#> $ C:List of 9
#> ..- attr(*, "class")= chr [1:2] "gg" "ggplot"
使用
purrr::walk()
purrr::walk(plot_list, print)
使用
purrr::iwalk()
purrr::iwalk(plot_list,
~ ggsave(plot = .x,
filename = paste0("Plot_", .y, ".png"),
type = 'cairo', width = 6, height = 6, dpi = 150)
)
如果需要,使用
cowplot::plot_grid()
library(cowplot)
do.call(plot_grid, c(plot_list,
align = "h",
axis = 'tb',
ncol = 3))
这篇关于在 R 中绘制多个图形的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!