在R中绘制多个图

时间:2018-10-20 04:19:10

标签: r ggplot2

因此,我想在每个位置同时绘制多个图,y轴上的访问次数为x,x轴上的天为数字,但是我不确定是否可以执行此操作?

data frame

因此,我可以通过将位置A替换为A来绘制位置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个位置,并且子集需要一些时间。任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:1)

您可以编写一个以数据框和Place为输入的函数,然后循环访问Place列中的所有值以创建相应的图。

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变量,创建图并使用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()

将所有图保存到PNG文件中
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))

reprex package(v0.2.1.9000)于2018-10-19创建

相关问题