han*_*nes 0 for-loop r ggplot2
我想先连续添加一个ggplot对象.但我不能得到以下所谓的简单代码:
数据框包含我想要绘制0到20期间的时间序列.
p <- ggplot(data=dfp, aes(x=seq(0,20,1), y=dfp) )
for (i in 1:7) {
p <- p + geom_line(aes(y=dfp[i]))
}
p
Run Code Online (Sandbox Code Playgroud)
最简单的方法是使用aes_string而不是aes.
# load necessary package
require(ggplot2)
# create sample data
dfp <- data.frame(matrix(rnorm(147), nrow=21))
# original plot (removed unnecessary call to y)
p <- ggplot(data=dfp, aes(x=seq(0,20,1)))
# loop
for (i in 1:7) {
# use aes_string with names of the data.frame
p <- p + geom_line(aes_string(y = names(dfp)[i]))
}
# print the result
print(p)
Run Code Online (Sandbox Code Playgroud)