1
votes

I have a data table with 2 names and 3 types for each name.

dt = CJ(as.Date(c('2000-01-01','2000-01-02','2000-01-03','2000-01-04')), c('A','B'), c('t1','t2','t3'))
setnames(dt, c('date','name','type'))
dt[, type := paste0(name, type)]
dt[, value := rnorm(n = .N) + (name == 'A')]


date           name type      value
1: 2000-01-01    A  At1  0.3872948
2: 2000-01-01    A  At2 -0.6147802
3: 2000-01-01    A  At3  2.2317864
4: 2000-01-01    B  Bt1  0.4979870
5: 2000-01-01    B  Bt2 -1.7946112
6: 2000-01-01    B  Bt3  0.7247306
7: 2000-01-02    A  At1  0.3148835
8: 2000-01-02    A  At2  0.1124225
9: 2000-01-02    A  At3  1.1758116
10: 2000-01-02    B  Bt1 -0.7068185
11: 2000-01-02    B  Bt2 -1.6968477
12: 2000-01-02    B  Bt3  0.4575144
....

Plot by types, but colour by name, so we get 3 red lines and 3 blue lines

ggplot(dt) + geom_line(aes(x = date, y = value, group = type, col = name))

Now I want to add two lines representing the means of each name

mdt = dt[, .(value = mean(value)), by = 'name,date']

ggplot(dt) + geom_line(aes(x = date, y = value, group = type, col = name)) + 
  geom_line(data = mdt, aes(x = date, y = value, col = name), size = 1.5)

This will use the exact same 2 colours for the individual lines as well as the mean lines. How can I specify different colours for the mean lines?

1
What do you want to do with legend? Four colours there?pogibas
Ideally, I'll use a slightly different colour for the mean lines, so I just need two legends "red-ish A, blue-ish B". But any configuration of legends would be fine to startjf328
You just need to put the colour argument outside of aes and map it to an explicit colour: geom_line(data = mdt, aes(x = date, y = value), col = "#000000", size = 1.5)dshkol

1 Answers

1
votes

Plot mdt lines with separate geom_line layers and specify colors in them.
For name A plot mean line using: geom_line(data = mdt[name == "A"], col = "#ff5a32") with redish color. For thinner lines specify similar color with scale_color_manual.

library(data.table)
library(ggplot2)

mdt <- dt[, .(value = mean(value)), by = .(name, date)]

ggplot(dt, aes(date, value)) + 
    geom_line(aes(group = type, col = name)) + 
    geom_line(data = mdt[name == "A"], col = "#ff5a32", size = 2) +
    geom_line(data = mdt[name == "B"], col = "#475cd3", size = 2) +
    scale_colour_manual(name = "Name", 
                        values = c("#ff987f", "#8c99e4")) +
    labs(x = "Date",
         y = "Value", 
         title = "Change in value over time") +
    theme_classic()

enter image description here