Is it possible to add a gradient fill to a density plot in ggplot2, such that the color in the chart changes along the x-axis? In this example below, the fill
argument appears to be ignored.
library(ggplot2)
ggplot(data.frame(x = rnorm(100)), aes(x = x, fill = x)) + geom_density()
There's always an option to compute density by hand:
set.seed(123)
x <- rnorm(100)
y <- density(x, n = 2^12)
ggplot(data.frame(x = y$x, y = y$y), aes(x, y)) + geom_line() +
geom_segment(aes(xend = x, yend = 0, colour = x)) +
scale_color_gradient(low = 'green', high = 'red')
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