ggplot - 根据数据中变量类型不断变化的变量设置线条颜色

ggplot - Set colour of lines depending on a variable with a changing presence of the variable type within the data

假设以下数据框:

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 1Type 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 1Type 2Type 3 的颜色,然后根据数据中存在的 Type 可变地使用各自定义的颜色.所以我可以预先定义颜色和 运行 脚本与新数据,而无需更改我的代码中的任何内容(假设 Type 1 应该是 blueType 2 应该对于三个数据帧的每个图,redType 3 应该是 black)。谢谢!

values 参数可以使用命名向量为相应的 Type.

赋值
library(ggplot2)

cols <- c('Type 1' = 'blue', 'Type 2' = 'red', 'Type 3' = 'black')

ggplot(mydf, aes(x = date, y = value, colour = type)) + geom_line() +
  scale_color_manual(name = 'Type',values= cols)

所以当你有所有类型的数据时,它看起来

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'))

当你缺少一些类型时,它仍然使用相同的颜色和相同的代码。

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'))