Breaks and labels are different lengths

I set five breaks and 5 labels in scale_color_continuous(breaks = c(1,2,3,4,5), labels = c("one", "two", "three", "four", "Five")). It is working well for two breaks and labels. However, when a breaks and labels is reduced to one by filtering , it says Breaks and labels are different lengths.

library(tidyverse)
mtcars1 <- mtcars %>% filter(gear == 5)
ggplot(mtcars1, aes(wt, mpg)) + geom_point(aes(color = gear)) + scale_color_continuous(breaks = c(1,2,3,4,5), labels = c("one", "two", "three", "four", "Five"))

Hi shafiul Welcome to the forum.

Your basic problem seems to be that gear has only one value.

mtcars1 
                mpg cyl  disp  hp drat    wt qsec vs am gear carb
Porsche 914-2  26.0   4 120.3  91 4.43 2.140 16.7  0  1    5    2
Lotus Europa   30.4   4  95.1 113 3.77 1.513 16.9  1  1    5    2
Ford Pantera L 15.8   8 351.0 264 4.22 3.170 14.5  0  1    5    4
Ferrari Dino   19.7   6 145.0 175 3.62 2.770 15.5  0  1    5    6
Maserati Bora  15.0   8 301.0 335 3.54 3.570 14.6  0  1    5    8

not sure why its bugging; it may be a genuine ggplot2 error you found; but there is a straightforward way to achieve the goal, using the idea -

  • A function that takes the breaks as input and returns labels as output. Also accepts rlang lambda function notation.

This would be like :

library(tidyverse)
mtcars1 <- mtcars %>% filter(gear ==5 )

ggplot(mtcars1, aes(wt, mpg)) +
  geom_point(aes(color = gear)) +
  scale_color_continuous(
    breaks = 1:5,
    labels = \(x)c("one","two","three","four","five")[x]
  )

Another approach is to add the limits argument.

ggplot(mtcars1, aes(wt, mpg)) + 
  geom_point(aes(color = gear)) + 
  scale_color_continuous(limits = c(1,5), 
                         breaks = c(1,2,3,4,5), 
                         labels = c("one", "two", "three", "four", "Five"))

Thanks Nirgrahamuk. Nice solution.

Thanks Scottyd22. Nice solution.

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.