AF7
AF7

Reputation: 3242

Steeper gradients in scale_gradientn

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?

Upvotes: 3

Views: 408

Answers (2)

makarand kulkarni
makarand kulkarni

Reputation: 301

you can use legend key height in theme set it as

 legend.key.height =  unit(0, 'lines')

and you are right some trial and error has to be done my plot looks as follows enter image description here

Upvotes: 0

Roland
Roland

Reputation: 132706

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

Upvotes: 2

Related Questions