Label minimum and maximum of scale fill gradient legend with text: ggplot2 Label minimum and maximum of scale fill gradient legend with text: ggplot2 r r

Label minimum and maximum of scale fill gradient legend with text: ggplot2


For scale_fill_gradientn() you should provide both arguments: breaks= and labels= with the same length. With argument limits= you extend colorbar to minimum and maximum value you need.

ggplot(df, aes(x, y, fill = z)) + geom_raster() +       scale_fill_gradientn(colours=topo.colors(7),na.value = "transparent",                           breaks=c(0,0.5,1),labels=c("Minimum",0.5,"Maximum"),                           limits=c(0,1))

enter image description here


User Didzis Elfert's answer slightly lacks "automatism" in my opinion (but it is of course pointing to the core of the problem +1 :).Here an option to programatically define minimum and maximum of your data.

Advantages:

  • You will not need to hard code values any more (which is error prone)
  • You will not need hard code the limits (which also is error prone)
  • Passing a named vector: You don't need the labels argument (manually map labels to values is also error-prone).
  • As a side effect you will avoid the "non-matching labels/breaks" problem
library(ggplot2)foo <- expand.grid(x = 0:5, y = 0:5)foo$z <- runif(nrow(foo))myfuns <- list(Minimum = min, Mean = mean, Maximum = max)ls_val <- unlist(lapply(myfuns, function(f) f(foo$z)))# you only need to set the breaks argument! ggplot(foo, aes(x, y, fill = z)) +  geom_raster() +  scale_fill_gradientn(    colours = topo.colors(7),    breaks = ls_val  )

# You can obviously also replace the middle value with sth elsels_val[2] <- 0.5names(ls_val)[2] <- 0.5ggplot(foo, aes(x, y, fill = z)) +  geom_raster() +  scale_fill_gradientn(    colours = topo.colors(7),    breaks = ls_val  )