I want to incrementally build a plot that contains several data series of different lengths. My goal is to be able to control the appearance of each data series, give them custom names and to have appropriate legends. My data series are of different lengths, so I cannot put them in a single dataframe. In the code below I expect 4 lines: the shortest will be red, the next ones will be blue, green and black respectively
library(ggplot2)
set.seed(12345)
plt <- ggplot()
colors <- c('red', 'blue', 'green', 'black')
for(i in seq(length(colors))) {
x <- seq(1, 2*i)
y <- x * i + rnorm(length(x))
df <- data.frame(x=x, y=y)
plt <- plt + geom_point(aes(x, y), data=df, color=colors[i]) +
geom_line(aes(x, y), data=df, color=colors[i])
}
print(plt)
This is what I get.
How can I give names to the lines and display a legend? Is there a better way to acheive my goal?