ggplot颜色以其他具有预定义调色板的列为条件

时间:2017-05-22 17:19:52

标签: r ggplot2 colors conditional

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

我在ggplot2中看到的有关条件颜色的答案建议使用scale_fill_manualscale_color_manual herehere手动指示颜色。< / p>

如果您要评估许多颜色类别,或者只是想使用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()

enter image description here

2 个答案:

答案 0 :(得分:3)

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

quote

enter image description here

答案 1 :(得分:1)

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

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

enter image description here