Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add colour gradient density plot R

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading