Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Steeper gradients in scale_gradientn

Tags:

r

colors

ggplot2

Using ggplot2 in R, I can obtain a discrete color scale like the following: https://i.sstatic.net/7g4mf.png

This can be generated as seen here.

However, it does not look great. I'd like ro remove the spacing between the levels, and I thought that maybe I could switch to a continuous color scale, using scale_gradientn() and having a very steep gradient between different colors. This way I could use a continuous color scale, which has labels in the right places and looks great, instead of a discrete one.

However, this is the best I could come up with:

library(ggplot2)
ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = density)) +
  scale_fill_gradientn(
    colours = c("red", "green", "blue", "yellow"), 
    values=c(0, 0.25, 0.25001, 0.5, 0.5001, 0.75, 0.75001,1)
  )

enter image description here

Which clearly is not good enough, as significant color shifting can be seen between the 4 levels.

Is this possible at all in ggplot2?

like image 384
AF7 Avatar asked Feb 07 '26 02:02

AF7


1 Answers

Just use a discrete scale:

library(ggplot2)
faithfuld$classes <- cut(faithfuld$density, c(-Inf, 0.01, 0.02, 0.03, Inf))
ggplot(faithfuld, aes(waiting, eruptions)) +
  geom_raster(aes(fill = classes)) +
  scale_fill_manual(name = "density",
                    values = c("red", "green", "blue", "yellow"),
                    labels = c(0.01, 0.02, 0.03, "")) +
  guides(fill = guide_legend(label.vjust = -0.2))

enter image description here

like image 137
Roland Avatar answered Feb 09 '26 08:02

Roland



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!