r - Dynamically create expression for ggplot legend? -
i want plot line graph, multiple lines, coloured depending on grouping variable. want set legend labels via scale
-command:
scale_color_manual(values = colors_values, labels = ...)
the legend labels following: "x^2", "x^3", "x^4" etc., range dynamically created. dynamically create expression label text, i.e.
"x^2"
should become x2"x^3"
should become x3
etc.
the amount of legend labels varies, thought as.expression(sprintf("x^%i", number))
, of course not work label
parameter scale
function.
i have searched google , stack overflow, however, haven't found working solution yet, hope can me here.
here's 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() (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 want change legend labels # lables = expresion??? )
i have legend labels x2, x3 , x4.
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's important ensure correct mapping if change values or labels in scale. thus, should use named vectors.
Comments
Post a Comment