在R中绘制多个图 [英] Plotting multiple graphs in R

查看:50
本文介绍了在R中绘制多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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来绘制位置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变量,创建图&使用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))

reprex软件包(v0.2.1.9000)创建于2018-10-19

Created on 2018-10-19 by the reprex package (v0.2.1.9000)

这篇关于在R中绘制多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆