r - 将绘图分配给循环中的变量
问题描述
我正在尝试创建 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()
我不知道的工作方式。
问题:
- 如果我想使用方法2,我应该如何修改逻辑?
- 人们说 using
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]]
推荐阅读
- python - 再次使用密钥列表从列表中创建字典
- php - 插件如何获取我网站的目录 URL
- scala - 如何在黄瓜套件之前/之后运行代码?
- android - Android 不导入/同步外部库
- python - 詹金斯管道虚拟环境插件与PythonEnv
- python - Flask Rest API - 如何在 python 请求中使用 Bearer API 令牌
- java - 在 Spring 中配置 Hibernate 模型发现
- ios - 如何快速调用 UnitySendMessage 方法?
- javascript - 突出显示一个元素(或字符),但实际上复制了一个不同的单词
- linphone - 为 Android 构建 liblinphone 4.0.0 时未找到核心包