在for循环中使用geom_line

时间:2015-01-09 01:44:04

标签: r for-loop 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  

2 个答案:

答案 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()

ggplot from tidy data

如果您还想要一个图例,请

colour=key添加到aes()来电。尝试运行部分管道以查看gather和其他位。