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

sh_*_*ent 0 r ggplot2 line-plot

假设以下数据框:

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
Run Code Online (Sandbox Code Playgroud)

我想创建一个自动代码,为每种类型创建一个线图并定义每条线的颜色。一般来说,我知道该怎么做:

require(ggplot2)
myplot <- ggplot(mydf, aes(x = date, y = value, colour = type)) + geom_line() +
  scale_color_manual(name = 'Type', values=c('blue', 'red'))
Run Code Online (Sandbox Code Playgroud)

但是,在另一个月运行代码时,数据框可能会发生变化。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
Run Code Online (Sandbox Code Playgroud)

再过一个月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
Run Code Online (Sandbox Code Playgroud)

如何设置 的颜色Type 1Type 2然后Type 3根据Type数据中存在的颜色不同地使用各自定义的颜色。因此,我可以预先定义颜色,然后使用新数据运行脚本,而无需更改代码中的任何内容(假设三个数据帧的每个图的Type 1should be blueType 2should beredType 3should be )。black谢谢!

Ron*_*hah 5

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)
Run Code Online (Sandbox Code Playgroud)

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

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'))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

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

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'))
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述