Search code examples
rggplot2labellegend

Add label between colorbar breaks in ggplot2


I am trying to create a figure with ggplot and would like to add category names between colorbar breaks (values). I am using a graduated colorbar using the scale_color_fermenter function, which I think makes it a bit tricky to do this.

Below is an example code

library('ggplot2')
ggplot(mtcars, aes(x=mpg, y=carb, color=disp)) + 
geom_point(size=3)+ 
scale_color_fermenter(breaks = c(100,300,400), palette = "Blues") #graduate colorbar

The resulting figure looks like this

enter image description here

I want to add categories (A, B, C, etc.) between the colorbar breaks (i.e., create categories for disp), such that

0<=A<100 
100<=B<300 
300<=C<400
400<=D<500 

The resulting figure looks like this (or similar)

enter image description here

I know I can add extra breaks and change the label. Something like the following

scale_color_fermenter(breaks=c(50,100,200,300,350,400,450,500), 
                      labels=c('A','100','B','300','C','400','D','500'))

But this would mess up the colorbar class (i.e., colorbar will have more colors), which is something I do not want.


Solution

  • Basically the same approach as by @zephryl but with some additional styling and fiddling and using ggtext::element_markdown just in case you want some additional styling for the text labels.

    • Using lineheight I add some padding between the tick and the category labels.
    • Using vjust I shift the labels so that the position of the tick labels corresponds approximately to the boundaries of the legend keys.
    library("ggplot2")
    
    mylabels <- function(x) {
      paste0(
        c(rep("", length(x) - 1), paste0("<span style='color: red'>", LETTERS[length(x) + 1], "</span><br>")),
        x,
        "<br><span style='color: red'>", LETTERS[seq_along(x)], "</span>"
      )
    }
    
    ggplot(mtcars, aes(x = mpg, y = carb, color = disp)) +
      geom_point(size = 3) +
      scale_color_fermenter(breaks = c(100, 300, 400), labels = mylabels, palette = "Blues") +
      theme(legend.text = ggtext::element_markdown(vjust = c(.85, .85, .55), lineheight = 1.25))