我想先后添加一行到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
答案 0 :(得分:5)
最简单的方法是使用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)
答案 1 :(得分:2)
在影子的回答中使用相同的dfp
:
library(tidyr)
library(dplyr)
然后:
dfp %>% gather() %>% group_by(key) %>%
mutate(x=1:n()) %>%
ggplot(aes(x=x, y=value,group=key)) + geom_line()
将colour=key
添加到aes()
来电。尝试运行部分管道以查看gather
和其他位。