Skip to content

scale_color_gradientn errors when using labels #5753

@tvatter

Description

@tvatter

I found a problem with scale_color_gradientn.

I expected to be able to use the labels argument to tweak the labels, but I must be doing something wrong.

Here is the code to reproduce what I believe to be a bug:

library(tidyverse)
library(scales)
#> 
#> Attaching package: 'scales'
#> The following object is masked from 'package:purrr':
#> 
#>     discard
#> The following object is masked from 'package:readr':
#> 
#>     col_factor

set.seed(1)
nyears = 20
df <- tibble( # a toy dataset
  year_idx = rep(1:nyears, each = 12),
  month = rep(1:12, nyears),
  passengers = rnorm(nyears * 12, mean = 10 * rep(1:nyears, each = 12))
)

years <- 1970:(1970 + nyears - 1)

ggplot(df, aes(x = month, y = passengers, color = year_idx, group = year_idx)) +
  geom_line() # works

ggplot(df, aes(x = month, y = passengers, color = year_idx, group = year_idx)) +
  geom_line() +
  scale_color_gradientn(colours = (scales::hue_pal())(9),
                        labels = function(idx) years[idx]) # errors
#> Error in `scale_color_gradientn()`:
#> ! `breaks` and `labels` have different lengths.

Created on 2024-03-06 with reprex v2.1.0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions