我知道在这个话题上已经有很多答案了。然而,对于一个新手来说,仍然有一些步骤我无法绕开。所以我们开始吧。希望你能帮我一把。
我想安排四个不同的情节2乘2。我使用的是ggplot,所以我不能使用par(mfrow=c(2,2)),但本质上是我想要做的。根据我所读到的,我应该使用gridExtra。这是我的密码:
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)
}
}数据样本:
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")我想我真正的问题是,当执行循环时,我不知道我的情节存储在哪里,所以我可以再次访问它们。
发布于 2020-05-05 22:34:45
您可以使用优秀的拼凑包:
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)

您也可以使用tidyr::pivot_longer和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)

发布于 2020-05-05 22:55:49
您需要将它们放在一个列表中,然后是grid.arrange,并且尽量不要使用get(),它有时会引起一些混乱(在我看来),我在下面使用了!!sym():
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
复制相似问题