MLEN
MLEN

Reputation: 2561

Drawing several "numeric" lines using ggplot

I have a dataset which contains 200 different groups, which can take some a between 0 and 200. I would like to draw a line for every group, so a total of 200 lines and have the legend to be "numeric". I know how to do this with a factor, but cant get it to work. Not the best example:

library(tidyverse)


df <- data.frame(Day = 1:100)
df  <- df %>% mutate(A = Day + runif(100,1,400) + rnorm(100,3,400) + 2500,
                     B = Day + rnorm(100,2,900) + -5000  , 
                     C = Day + runif(100,1,50) + rnorm(100,1,1000) -500,
                     D = (A+B+C)/5 - rnorm(100, 3,450) - 2500)

df <- gather(df, "Key", "Value", -Day)
df$Key1 <- apply(df, 1, function(x) which(LETTERS == x[2]))

ggplot(df, aes(Day, Value, col = Key)) + geom_line() # I would to keep 4 lines, but would like have the following legend

ggplot(df, aes(Day, Value, col = Key1)) + geom_line() # Not correct lines
ggplot(df, aes(Day, Value)) + geom_line(aes(col = Key1)) # Not correct lines

Likely a duplicate, but I cant find the answer and guess there is something small that is incorrect.

Upvotes: 1

Views: 50

Answers (1)

user3640617
user3640617

Reputation: 1576

Is this what you mean? I'm not sure since you say you want 200 lines, but in your code you say you want 4 lines.

ggplot(df, aes(Day, Value, group = Key, col=Key1)) + geom_line()

Using group gives you the different lines, using col gives you the different colours.

Upvotes: 3

Related Questions