Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Applying a gradient fill on a density plot in ggplot2

Tags:

r

ggplot2

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()
like image 468
Phil Avatar asked Aug 14 '17 15:08

Phil


1 Answers

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

enter image description here

like image 124
tonytonov Avatar answered Oct 13 '22 00:10

tonytonov