Dynamically create expression for ggplot legend?
I want to plot a line graph with multiple lines colored based on a grouping variable. Now I want to set legend labels using the scale
-command:
scale_color_manual(values = colors_values, labels = ...)
The legend characters are "x ^ 2", "x ^ 3", "x ^ 4", etc., where the range is dynamically created. Now I would like to dynamically create an expression as a label text i.e.
-
"x^2"
should become x 2 -
"x^3"
should become x 3
and etc.
The number of legend labels changes, so I thought of something like as.expression(sprintf("x^%i", number))
that, of course, doesn't work as a parameter label
to a function scale
.
I've searched google and Stack Overflow, however I haven't found a working solution yet, so hope someone can help me here.
Here's a reproducible example:
poly.term <- runif(100, 1, 60)
resp <- rnorm(100, 40, 5)
poly.degree <- 2:4
geom.colors <- scales::brewer_pal(palette = "Set1")(length(poly.degree))
plot.df <- data.frame()
for (i in poly.degree) {
mydat <- na.omit(data.frame(x = poly.term, y = resp))
fit <- lm(mydat$y ~ poly(mydat$x, i, raw = TRUE))
plot.df <- rbind(plot.df, cbind(mydat, predict(fit), sprintf("x^%i", i)))
}
colnames(plot.df) <- c("x","y", "pred", "grp")
ggplot(plot.df, aes(x, y, colour = grp)) +
stat_smooth(method = "loess", se = F) +
geom_line(aes(y = pred))
scale_color_manual(values = geom.colors
# here I want to change legend labels
# lables = expresion???
)
I would like the legend labels to be x 2 x 3 and x 4 .
ggplot(plot.df, aes(x, y, colour = grp)) +
stat_smooth(method = "loess", se = F) +
geom_line(aes(y = pred)) +
scale_color_manual(values = setNames(geom.colors,
paste0("x^",poly.degree)),
labels = setNames(lapply(poly.degree, function(i) bquote(x^.(i))),
paste0("x^",poly.degree)))
It is important to ensure correct display if you change values ββor labels on the scale. Thus, you should always use named vectors.