Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing colour of existing geom, with no grouping

Tags:

r

ggplot2

This is likely just a blunder from my side, not remembering how to do this. Non-the-less. Imagine a scenario where you have a function generating a ggplot. You give no grouping, and the points are all coloured black. For simplicity, imagine the plot below is the one returned.

library(ggplot2)
data(mtcars)
p <- ggplot(mtcars, aes(y = mpg, x = hp)) + 
      geom_point()

How would I now change the colour of the points in p, without modifying the function that generated the plot itself. Eg. changing the code to geom_point(col = "green") would not be the an option.

like image 697
Oliver Avatar asked Oct 15 '25 17:10

Oliver


1 Answers

An easy way to do it is to add a dummy aesthetic mapping after the fact:

 p + aes(color = "forestgreen") + scale_color_identity(guide = guide_none())

enter image description here

A more permanent alternative, which is the equivalent of going back and writing the color = "forestgreen" parameter back into the geom_point call is:

p$layers[[1]]$aes_params <- list(colour = "forestgreen")
like image 158
Allan Cameron Avatar answered Oct 17 '25 09:10

Allan Cameron



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!