2

I would like to modify the guide_colorbar of a continuous aesthetic with character descriptions, e.g., 'low' and 'high', instead of actual numbers. This can be especially useful when using one legend or colorbar for multiple plots (heatmaps, e.g, geom_bin2d).

Here an example.

Example

Say given dummy data:

dd <- data.frame(xx=rnorm(100),yy=rnorm(100),zz=rep(1:10,10))

I can do the usual

ggplot(dd,aes(xx,yy,color=zz))+
  geom_point()+
  viridis::scale_color_viridis(option='A',direction=-1)

and hide colorbar annotations using

guides(color=guide_colorbar(ticks=F,label=F,title=element_blank()))

Another approach I tried is modifying the color aesthetics with

factor(zz,labels=c('low',2:9,'high'))
...
guides(color=guide_legend(override.aes=list(size=5,shape=15)))

and plotting as discrete. Also not really desired.

How do I add customized text to guide_colorbar? Or: Is there a way to convert a discrete legend to a colorbar and keeping the character labels?

tjebo
  • 21,977
  • 7
  • 58
  • 94
leze
  • 100
  • 9
  • 1
    does this [question](https://stackoverflow.com/questions/35994165/add-discrete-labels-to-ggplot2-plot-with-continuous-scale) help? – Atreyagaurav Dec 30 '19 at 13:53

1 Answers1

6

Here one way how to add string labels to a color bar, with programmatic calculation of the breaks.

I am using a named list of functions, with which I create a named vector of values which I use for the breaks. If you don't name the vector, you will need to specify the labels.

library(ggplot2)

set.seed(42)
dd <- data.frame(xx = rnorm(100), yy = rnorm(100), zz = rep(1:10, 10))

## using a named list, resulting in a named vector for the breaks
myfuns_nam <- list(min = min, med = median, max = max)

list_val <- lapply(myfuns_nam, function(f) f(dd$zz))

ggplot(dd, aes(xx, yy, color = zz)) +
  geom_point() +
  scale_color_gradient2(breaks = unlist(list_val))


# you can also not name the function list, but then you will need to specify the labels
# list of functions to calculate the values where you want your breaks
myfuns <- list(min, median, max)
# use this list to make a list of your breaks
list_val2 <- lapply(myfuns, function(f) f(dd$zz))

# to use the list, unlist it first
ggplot(dd, aes(xx, yy, color = zz)) +
  geom_point() +
  scale_color_gradient2(breaks = unlist(list_val2), labels = c("min", "med", "max"))
tjebo
  • 21,977
  • 7
  • 58
  • 94