Home > Back-end >  changing labels works for `guide_colourbar` but not for `guide_coloursteps` in `ggplot2` R
changing labels works for `guide_colourbar` but not for `guide_coloursteps` in `ggplot2` R

Time:10-08

I'm trying to change the label of legend to censor those excessively large values in ggplot2. My trick works perfectly well for guide_colourbar, but the same code does not work for guide_coloursteps. Below is a reproducible example.

library(ggplot2)

ggplot(data = mtcars, 
         aes(x = mpg, y = drat, color = gear))  
  geom_point()   
  scale_color_continuous(
    type = "viridis", 
    option = 'A', 
    direction = -1, 
    limits = c(3, 4), 
    oob = scales::squish,
    breaks = seq(3, 4, 0.2), 
    labels = c(seq(3, 3.8, 0.2), '>4'),
    guide = guide_colourbar(
      show.limits = TRUE))

enter image description here

However, the code does not work when I change guide_colourbar into guide_coloursteps:

ggplot(data = mtcars, 
       aes(x = mpg, y = drat, color = gear))  
  geom_point()   
  scale_color_continuous(
    type = "viridis", 
    option = 'A', 
    direction = -1, 
    limits = c(3, 4), 
    oob = scales::squish,
    breaks = seq(3, 4, 0.2), 
    labels = c(seq(3, 3.8, 0.2), '>4'),
    guide = guide_coloursteps(
      show.limits = TRUE))

# Error in `f()`:
# ! Breaks and labels are different lengths
# Run `rlang::last_error()` to see where the error occurred.

The error persists even when I change the length of labels by add/deleting one or two labels.

Any advice would be appreciated.

CodePudding user response:

I have no clue why the scale behaves different for the different type of guides but a workaround would be to pass a custom function to the labels argument which avoids having to pass a hard-coded vector of labels:

library(ggplot2)

ggplot(data = mtcars, 
       aes(x = mpg, y = drat, color = gear))  
  geom_point()   
  scale_color_continuous(
    type = "viridis", 
    option = 'A', 
    direction = -1, 
    limits = c(3, 4), 
    oob = scales::squish,
    breaks = seq(3, 4, 0.2), 
    labels = ~ ifelse(.x < 4, .x, '>4'),
    guide = guide_colorsteps(
      show.limits = TRUE))

  • Related