【问题标题】:ggplot2 colors association problem with ifelseggplot2与ifelse的颜色关联问题
【发布时间】:2021-06-16 20:33:46
【问题描述】:

这是我的 df 结构

Date VAR  Value
    1    A    0.1 
    2    A    0.1 
    2    B1   0.2 
    2    B2   0.3 
    2    B3   0.2 
    3    A    0.1
    4    A    0.1
    5    A    0.1
    5    B4   0.4

我可以绘制它们。但我有一个问题。我希望每个 B 只有一种颜色。我不能随便写,因为我有很多专栏。所以我需要grepl函数。 我试过这样。但它工作不正常。

print(ggplot(df, aes(date,value)) 
      + geom_line(aes(colour = ifelse(grepl("B", VAR) == T, "green", "blue"))) 

我该如何处理?

【问题讨论】:

  • 很抱歉,它不起作用。我昨天找到了解决方案。我不得不一起使用填充和颜色。打印(ggplot(df,aes(日期,值,填充=变量,颜色=颜色))+ geom_line()

标签: r if-statement ggplot2 colors time-series


【解决方案1】:

使用颜色创建一个新列并使用scale_color_identity

library(dplyr)
library(ggplot2)

df %>%
  mutate(color = ifelse(grepl("B", VAR), "green", "blue")) %>%
  ggplot(aes(Date, Value, color = color)) + geom_line() + 
  scale_color_identity()

【讨论】:

    猜你喜欢
    • 2016-07-28
    • 2021-11-29
    • 2015-01-01
    • 2016-09-09
    • 1970-01-01
    • 2022-10-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-25
    相关资源
    最近更新 更多