简体   繁体   中英

How to draw several lines with ggplot?

This code draws 2 lines

dd = list(data.frame(rates=1:5), data.frame(rates=2:6), data.frame(rates=3:7))
library(ggplot2)
library(zoo)
g = ggplot(, aes(1:5))
g <- g + geom_line(aes(y = dd[[1]]$rate[index(dd[[1]]) <= 5]), colour="#000000")
g <- g + geom_line(aes(y = dd[[2]]$rate[index(dd[[2]]) <= 5]), colour="#000000")
g

在此处输入图片说明

But this code draws 1 line (for last i, 2)

dd = list(data.frame(rates=1:5), data.frame(rates=2:6), data.frame(rates=3:7))
g = ggplot(, aes(1:5))
foreach (i = 1:2) %do% {
  g <- g + geom_line(aes(y = dd[[i]]$rate[index(dd[[i]]) <= 5]), colour="#000000")
}
g

在此处输入图片说明

Example on r-fiddle

Why and how to fix?

As I alluded to, I think you should simply stop using ggplot2 so strangely:

g = ggplot(, aes(1:5))
foreach (i = 1:2) %do% {
  g <- g + geom_line(data = dd[[i]],aes(y = rates), colour="#000000")
}
g

This produces two lines just like your first example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM