Reputation: 7351
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?
Upvotes: 1
Views: 2952
Reputation: 28339
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()
Upvotes: 1