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:

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

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