我正在尝试创建2条线图。
但是我注意到使用for
循环会生成两个图y=mev2
(而不是基于的图y=mev1
和基于的图y=mev2
)。
下面的代码显示了此处的观察结果。
mev1 <- c(1,3,7)
mev2 <- c(9,8,2)
Period <- c(1960, 1970, 1980)
df <- data.frame(Period, mev1, mev2)
library(ggplot2)
# Method 1: Creating plot1 and plot2 without using "for" loop (hard-code)
plot1 <- ggplot(data = df, aes(x=Period, y=unlist(as.list(df[2])))) + geom_line()
plot2 <- ggplot(data = df, aes(x=Period, y=unlist(as.list(df[3])))) + geom_line()
# Method 2: Creating plot1 and plot2 using "for" loop
for (i in 1:2) {
y_var <- unlist(as.list(df[i+1]))
assign(paste("plot", i, sep = ""), ggplot(data = df, aes(x=Period, y=y_var)) + geom_line())
}
似乎是由于某种ggplot()
我不了解的工作方式所致。
题:
assign()
不是“ R风格”,所以我想知道还有什么替代方法吗?说,使用list
?没有tidyverse
添加命令的可能答案是:
library(ggplot2)
y_var <- colnames(df)
for (i in 1:2) {
assign(paste("plot", i, sep = ""),
ggplot(data = df, aes_string(x=y_var[1], y=y_var[1 + i])) +
geom_line())
}
plot1
plot2
您可以使用aes_string
。希望对您有所帮助。
编辑1
如果要在列表中存储图,可以使用以下方法:
初始化您的列表:
n <- 2 # number of plots
list_plot <- vector(mode = "list", length = n)
names(list_plot) <- paste("plot", 1:n)
填充 :
for (i in 1:2) {
list_plot[[i]] <- ggplot(data = df, aes_string(x=y_var[1], y=y_var[1 + i])) +
geom_line()
}
显示方式
list_plot[[1]]
list_plot[[2]]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句