【问题标题】:ggplot - Set colour of lines depending on a variable with a changing presence of the variable type within the dataggplot - 根据变量设置线条颜色,数据中变量类型的存在发生变化
【发布时间】: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 用于三个数据帧的每个图)。谢谢!

【问题讨论】:

    标签: r ggplot2 line-plot


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多