In ggplot2 version 2.2.0, E.g.:
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = rep(0.5, 3))
# x y alpha
# 1 1 1 0.5
# 2 2 2 0.5
# 3 3 3 0.5
ggplot(tmp_df, aes(x, y, alpha = alpha)) +
geom_bar(stat = 'identity') +
scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'))
Produces the error:
Error in f(..., self = self) : Breaks and labels are different lengths
Manually removing the extra alpha values in scale_alpha
fixes the problem, but surely this can be handled some how by ggplot?
You must supply the limits for the scale because tmp_df$alpha
is always the same, and ggplot
does not know the 'range' of the scale.
library(ggplot2)
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = rep(0.5, 3))
tmp_df
#> x y alpha
#> 1 1 1 0.5
#> 2 2 2 0.5
#> 3 3 3 0.5
ggplot(tmp_df, aes(x, y, alpha = alpha)) +
geom_bar(stat = 'identity') +
scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'), limits = c(0, 1))
If the alpha
dimension has a range itself, limits are no longer necessary, but note the in the following example the first break
is ignored, as it is outside the range. limits
would again be necessary if you want to include it.
tmp_df <- data.frame(x = 1:3, y = 1:3, alpha = seq(.5, 1.5, .5))
tmp_df
#> x y alpha
#> 1 1 1 0.5
#> 2 2 2 1.0
#> 3 3 3 1.5
ggplot(tmp_df, aes(x, y, alpha = alpha)) +
geom_bar(stat = 'identity') +
scale_alpha(breaks = c(0.25, 0.5, 1), labels = c('a', 'b', 'c'))