【问题标题】:ggplot color conditional on other column with predefined color paletteggplot 颜色以具有预定义调色板的其他列为条件
【发布时间】:2017-10-22 10:54:26
【问题描述】:

我想使用条件颜色创建带有ggplot2 的图表,这样如果数据点符合另一列上的条件,它将是"green",否则,它将遵循预定义的调色板。

我在 SO 中看到的关于ggplot2 中条件颜色的答案建议使用scale_fill_manualscale_color_manual herehere 手动指示颜色。

如果您有许多颜色类别要评估,或者只是想使用来自RColorBrewerViridis 的那些漂亮的预定义调色板之一,这并不理想。

这是我尝试的可重现示例:

library(ggplot2)
library(RColorBrewer)

# get data
  data("mtcars")

ggplot(mtcars, aes(x=qsec, y=hp,  color= ifelse( cyl < 6, "green", factor(carb)) )) +
  scale_colour_brewer( type = "seq", palette = "Reds") +
  geom_point() +
  theme_bw()

【问题讨论】:

    标签: r ggplot2 colors conditional


    【解决方案1】:

    如何添加一个额外的点图层,其中仅包含您想要的特定颜色的数据子集?

    mtcars$condition <- with(mtcars, ifelse(cyl < 6, 1, 0))
    
    ggplot(mtcars, aes(x=qsec, y=hp,  color= factor(carb))) +
      geom_point() + 
      geom_point(data = subset(mtcars, condition == 1), color = "green") +
      scale_colour_brewer( type = "seq", palette = "Reds") +
      theme_bw()
    

    【讨论】:

    • 感谢您回答@Daniel。我认为这可能是最直接的解决方案,我投票赞成你回答,但我已将答案授予马修,因为他的回答更完整,因为如果图表在图例上很明显,则修改非常重要用于传达信息。谢谢!
    • 啊...好吧。我的印象是你不想修改传说。我有一个与 Mike 非常相似的解决方案,但我认为传奇保持标准是首选。
    【解决方案2】:

    另一种选择,它不像添加另一层那么短,但我认为情节更清晰(你没有重叠点)。

    df <- mtcars
    df$col <- ifelse( df$cyl < 6, "cyl < 6", as.character(df$carb))
    non_green <- unique(df$col[df$col != "cyl < 6"])
    non_green <- non_green[order(non_green)]
    
    ggplot(df, aes(x=qsec, y=hp,  colour= col )) +
      scale_color_manual(values = c(setNames(brewer.pal(length(non_green), name = "Reds"), non_green), "cyl < 6" = "green")) +
      geom_point() +
      theme_bw()
    

    【讨论】:

      猜你喜欢
      • 2012-12-21
      • 1970-01-01
      • 2022-08-03
      • 1970-01-01
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 2021-11-23
      • 2012-04-07
      相关资源
      最近更新 更多