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

ggplot color conditional on other column with predefined color palette

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

我在 ggplot2 中看到的关于条件颜色的答案建议使用 scale_fill_manualscale_color_manual and here.

手动指示颜色

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

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

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

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

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

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

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