Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I colour the fill of ggplot stat_density with a gradient? [duplicate]

Tags:

r

ggplot2

I have a set of data which I want to plot with ggplot2's stat_density. The data ranges from -1000 to 1000 and I wanted the plot to be coloured with fill as a gradient, which goes from blue (-1000), to white (zero) and red (+1000). How do I do that? As a picture, it would be something like this:

plot

like image 404
J. Pereira Avatar asked Dec 28 '25 19:12

J. Pereira


1 Answers

I think you can do this with stat_density, but I leave this as an exercise for you. You could also calculate the density outside of ggplot2.

Anyway, use geom_segment and scale_colour_gradient2 like this:

library(ggplot2)
DF <- data.frame(x=seq(-3, 3, 1e-2))
DF$y <- dnorm(DF$x)

ggplot(DF, aes(x=x, y=y)) +
  geom_segment(aes(xend=x, yend=0, colour=abs(x)^0.7*sign(x))) +
  geom_line() +
  scale_colour_gradient2(low=scales::muted("blue", l=60), 
                         mid=scales::muted("green", l=60), 
                         high=scales::muted("red", l=60))

enter image description here

like image 174
Roland Avatar answered Dec 31 '25 07:12

Roland



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!