首页 > 解决方案 > 将绘图分配给循环中的变量

问题描述

我正在尝试创建 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()我不知道的工作方式。

问题:

标签: rggplot2

解决方案


未添加命令的一种可能答案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]]

推荐阅读