【发布时间】:2019-12-13 10:04:05
【问题描述】:
我正在尝试创建 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?
【问题讨论】:
-
实现方法 - 将宽转换为长并绘制
ggplot(reshape2::melt(df, "Period"), aes(Period, value, color = variable)) + geom_line()