I have a code similar to this:
x <- rnorm(100)
y <- density(x, n = 1000)
plot(y)
polygon(y,col="red")
However, I would also like to add a colour gradient to a density plot in basic R, particularly using a palette such as the Spectral from blue to red. In this way, the output would look like this:
I appreciate any help! Thanks!
>Solution :
You could use segments() to add countless line segments with gradient colours.
x <- rnorm(100)
y <- density(x, n = 1000)
plot(y)
segments(y$x, 0, y$x, y$y, col = hcl.colors(1000, "Spectral", rev = TRUE))
polygon(y)

