【发布时间】:2020-03-28 18:47:29
【问题描述】:
假设如下数据框:
mydf <- data.frame(date = as.Date(rep(c('2019-11-01', '2019-10-01'), 2)),
value = c(10, 15, 8, 4),
type = c('Type 1', 'Type 1', 'Type 2', 'Type 2'))
print(mydf)
date value type
1 2019-11-01 10 Type 1
2 2019-10-01 15 Type 1
3 2019-11-01 8 Type 2
4 2019-10-01 4 Type 2
我想创建一个自动代码,它为每种类型创建一个线图并定义每条线的颜色。一般来说,我知道该怎么做:
require(ggplot2)
myplot <- ggplot(mydf, aes(x = date, y = value, colour = type)) + geom_line() +
scale_color_manual(name = 'Type', values=c('blue', 'red'))
但是,在另一个月运行代码时,数据框可能会发生变化。数据框中可能有一个Type 3:
mydf <- data.frame(date = as.Date(rep(c('2019-11-01', '2019-10-01'), 3)),
value = c(10, 15, 8, 4, 12, 8),
type = c('Type 1', 'Type 1', 'Type 2', 'Type 2', 'Type 3', 'Type 3'))
print(mydf)
date value type
1 2019-11-01 10 Type 1
2 2019-10-01 15 Type 1
3 2019-11-01 8 Type 2
4 2019-10-01 4 Type 2
5 2019-11-01 12 Type 3
6 2019-10-01 8 Type 3
再过一个月Type 1 或Type 2 可能不在数据中:
mydf <- data.frame(date = as.Date(rep(c('2019-11-01', '2019-10-01'), 2)),
value = c(10, 15, 8, 4),
type = c('Type 1', 'Type 1', 'Type 3', 'Type 3'))
print(mydf)
date value type
1 2019-11-01 10 Type 1
2 2019-10-01 15 Type 1
3 2019-11-01 8 Type 3
4 2019-10-01 4 Type 3
如何设置Type 1、Type 2 和Type 3 的颜色,然后根据数据中存在的Type 可变地使用各自定义的颜色。所以我可以预先定义颜色并使用新数据运行脚本,而无需更改我的代码中的任何内容(假设 Type 1 应该是 blue,Type 2 应该是 red 和 Type 3 应该是black 用于三个数据帧的每个图)。谢谢!
【问题讨论】: