在ggplot2中的密度图上应用渐变填充

Phi*_*hil 5 r ggplot2

是否可以在ggplot2中的密度图上添加渐变填充,以使图表中的颜色沿x轴变化?在下面的示例中,该fill参数似乎被忽略。

library(ggplot2)
ggplot(data.frame(x = rnorm(100)), aes(x = x, fill = x)) + geom_density()
Run Code Online (Sandbox Code Playgroud)

ton*_*nov 5

总有一个选项可以手动计算密度:

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')
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明