ggplot2 - R: Extract scale name from ggplot object -


i wondering how extract scale name (i.e., legend name) ggplot object in general way possible. general, mean extracts same thing no matter how changed scale name, whether using name within scale function or using labs.

for instance:

library("ggplot2") set.seed(3489243) rho <- round(rnorm(25, 0, 5)) profit <- 0.5 + 0.3 * rho + rnorm(25, 0, 1) betaadjusted <- factor(c(rep(true, 15), rep(false, 10))) returns.both <- data.frame(rho, profit, betaadjusted) p1 <- ggplot(aes(x=rho, y=profit, shape = betaadjusted),         data=returns.both) +  geom_point() + scale_shape_discrete(name = "is beta adjusted?") p2 <- ggplot(aes(x=rho, y=profit, shape = betaadjusted),         data=returns.both) +  geom_point() + labs(shape = "is beta adjusted?") 

i want extract text is beta adjusted p1 , p2 using same code. possible? using labs(p2) gives me text under labels list using labs(p1) gives me text under scales list. don't want have @ 2 places same text depending on user input. after all, p1 , p2 produces same looking graph.

this solution depends heavily on scales implementation, use caution (as ggplot2 might change @ point).

p <- qplot(vs, wt, shape = factor(gear), color = factor(am), data = mtcars)  guide_names <- function(p, aes = c("shape", "colour", "size")) {   sc <- as.list(p$scales)$scales   nms <- lapply(sc, "[[", "name")   if (length(nms) > 0) names(nms) <- lapply(sc, "[[", "aesthetics")   modifylist(p$labels[names(p$labels) %in% aes], nms) }  guide_names(p) # $colour # [1] "factor(am)" #  # $shape # [1] "factor(gear)"  guide_names(p + labs(shape = "a") + labs(color = "b")) # $colour # [1] "b" #  # $shape # [1] "a"  guide_names(p + scale_shape_discrete(name = "s") + scale_color_discrete(name = "c")) # $colour # [1] "c" #  # $shape # [1] "s"  # if both specified, scale_* prefered guide_names(p + labs(shape = "a") + scale_shape_discrete(name = "s")) # $shape # [1] "s" #  # $colour # [1] "factor(am)" 

Comments

Popular posts from this blog

java - Andrioid studio start fail: Fatal error initializing 'null' -

android - Gradle sync Error:Configuration with name 'default' not found -

StringGrid issue in Delphi XE8 firemonkey mobile app -