ggplot multiple figures gridExtra

对着背影说爱祢 提交于 2020-05-17 06:05:10

问题


I know there are a lot of answers already on this topic. However, for a newbiw there are still some steps I can't get around. So here we go. Hope you can help me out.

I want to arrange four different plots 2 by 2. I'm using ggplot, so I can't use par(mfrow=c(2,2)) But it's essentially the same I want to do. From what I've read I should use the gridExtra. SO here is my code:

Plot_Graph <- function(DF, na.rm = TRUE){
  nm = names(DF)[-1]
  for (i in nm) {
   p <- ggplot(DF, aes(x = Date, y = get(i))) +
           geom_line() + 
           scale_x_date(minor_breaks = "1 year") +
           xlab("Year") + 
           ylab("Stock price US$") +
           ggtitle(paste(i)) +
           theme_bw()
   grid.arrange(p)
  }
}

Data sample:

structure(list(Date = structure(c(10960, 10961, 10962, 10963, 
10966), class = "Date"), AAPL = c(1, 1.01463414634146, 0.926829268292683, 
0.970731707317073, 0.953658536585366), GE = c(1, 0.998263888888889, 
1.01159722222222, 1.05076388888889, 1.05034722222222), SPY = c(1, 
1.00178890876565, 0.985688729874776, 1.04293381037567, 1.04651162790698
), WMT = c(1, 0.976675478152698, 0.990359197636448, 1.06515316436013, 
1.04571606282071)), row.names = c(NA, 5L), class = "data.frame")

I guess my problem really is, that I don't know where my plots are stored at, when doing the loop, so I can access them again.


回答1:


You can use the excellent patchwork package:

library(ggplot2)
library(patchwork)

nm <-  names(DF)[-1]

plots <- lapply(nm, function(x) {
  ggplot(DF, aes(x = Date, y = get(x))) +
    geom_line() + 
    scale_x_date(minor_breaks = "1 year") +
    xlab("Year") + 
    ylab("Stock price US$") +
    ggtitle(x) +
    theme_bw()
})

Reduce(`+`, plots) + plot_layout(nrow = 2)

Alternately you can use tidyr::pivot_longer and facet:

library(ggplot2)
library(tidyr)

DF %>% 
  pivot_longer(-Date) %>% 
  ggplot(aes(Date, value)) +
  geom_line() + 
  scale_x_date(minor_breaks = "1 year") +
  xlab("Year") + 
  ylab("Stock price US$") +
  theme_bw() +
  facet_wrap(~name)




回答2:


You need to place them in a list then grid.arrange, and try not to use get(), it can cause some chaos at times (in my opinion), I used !!sym() below:

Plot_Graph <- function(DF, na.rm = TRUE){
nm = names(DF)[-1]
plts = lapply(nm,function(i){
   p <- ggplot(DF, aes(x = Date, y = !!sym(i))) +
           geom_line() + 
           scale_x_date(minor_breaks = "1 year") +
           xlab("Year") + 
           ylab("Stock price US$") +
           ggtitle(paste(i)) +
           theme_bw()
    return(p)
   })
grid.arrange(grobs=plts,ncol=2)   
}



来源:https://stackoverflow.com/questions/61624122/ggplot-multiple-figures-gridextra

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!