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:
Asked
Active
Viewed 2,155 times
3

Tyler Rinker
- 108,132
- 65
- 322
- 519

J. Pereira
- 103
- 1
- 7
1 Answers
6
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))

Roland
- 127,288
- 10
- 191
- 288