Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot color conditional on other column with predefined color palette

I would like to create a chart with ggplot2 using a conditional color so that if the data point respect a condition on another column it will be "green", otherwise, it will follow a predefined color palette.

The answers I've seen in SO about conditional color in ggplot2 suggest to manually indicate colors using scale_fill_manual or scale_color_manual here and here.

and this is not really ideal if you have many color categories to assess or just want to use a one of those nice-looking predefined color palettes from RColorBrewer or Viridis.

Here is my reproducible example with my attempt:

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

like image 963
rafa.pereira Avatar asked Oct 21 '25 05:10

rafa.pereira


1 Answers

How about adding an additional points layer with just the subset of data you want in the specific color?

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

enter image description here

like image 182
Daniel Anderson Avatar answered Oct 23 '25 17:10

Daniel Anderson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!