scale_color_stepsn() will not accept expression vector for scale labels
An error is generated when attempting to specify color scale labels as a plotmath expression vector. The error is also generated when using scale_fill_stepsn(). I expected the color scale labels to be rendered using plotmath.
Here is code to reproduce the bug:
library(ggplot2)
data.frame(x = 1:5, y = 1:5) |>
ggplot(aes(x = x, y = y, color = y))+
geom_text(label = parse(text = paste0("x^", 1:5)))+
scale_color_stepsn(breaks = 1:5,
colors = c("red", "orange", "yellow","green", "blue"),
labels = parse(text = paste0("x^", 1:5)))
#> Error in `vec_size()`:
#> ! `x` must be a vector, not an expression vector.
Created on 2024-07-17 with reprex v2.1.0
I am able to achieve the desired result by providing a list-vector of expressions instead. If this is the intended behavior then I think the help entry should be updated accordingly. See reprex:
library(ggplot2)
data.frame(x = 1:5, y = 1:5) |>
ggplot(aes(x = x, y = y, color = y))+
geom_text(label = parse(text = paste0("x^", 1:5)))+
scale_color_stepsn(breaks = 1:5,
colors = c("red", "orange", "yellow","green", "blue"),
labels = as.list(parse(text = paste0("x^", 1:5))))
#> Warning in is.na(x): is.na() applied to non-(list or vector) of type
#> 'expression'

Created on 2024-07-17 with reprex v2.1.0
Thanks for the report! I'm suspecting that guide_coloursteps() probably doesn't convert vectors-expressions to list-expressions. The {vctrs} package can cope with list-expressions but not vector-expressions, which is what causes the error. This shouldn't be redocumented but fixed in the guide.
In addition, the following should also work but doesn't:
library(ggplot2)
data.frame(x = 1:5, y = 1:5) |>
ggplot(aes(x = x, y = y, color = y))+
geom_text(label = paste0("x^", 1:5), parse = TRUE)+
scale_color_stepsn(
breaks = 1:5,
colors = c("red", "orange", "yellow","green", "blue"),
labels = parse(text = paste0("x^", 1:5)),
guide = guide_bins()
)
#> Error in `scale_color_stepsn()`:
#> ! `breaks` and `labels` have different lengths.
Created on 2024-07-18 with reprex v2.1.1