Home > Net >  Add colour gradient density plot R
Add colour gradient density plot R

Time:09-03

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:

enter image description here

I appreciate any help! Thanks!

CodePudding user response:

You could use segments() to add countless line segments with gradient colours.

x <- rnorm(100)
dens <- density(x, n = 1000)
plot(dens)
segments(dens$x, 0, dens$x, dens$y, col = hcl.colors(1000, "Spectral", rev = TRUE))
polygon(dens)

enter image description here

  • Related