R:从ggplot对象中提取比例名称

时间:2015-06-29 14:49:25

标签: r ggplot2 data-visualization

我想知道如何以最一般的方式从ggplot对象中提取比例名称(即图例名称)。大多数情况下,我的意思是,无论您如何更改比例名称,无论是在name函数中使用scale还是使用labs,它都会提取相同的内容。

例如:

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?")

我想使用相同的代码从Is Beta Adjustedp1中提取文本p2。那可能吗?使用labs(p2)为我提供了标签列表下的文字,但是使用labs(p1)为我提供了比例列表下的文字。我不想根据用户输入查看相同文本的两个位置。毕竟,p1p2生成相同的图表。

3 个答案:

答案 0 :(得分:3)

此解决方案在很大程度上取决于比例实现,因此请谨慎使用(因为ggplot2可能会在某些时候改变它)。

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 are specified, scale_* is prefered
guide_names(p + labs(shape = "A") + scale_shape_discrete(name = "S"))
# $shape
# [1] "S"
# 
# $colour
# [1] "factor(am)"

答案 1 :(得分:1)

这是你的想法吗?

 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?")


lapply(list(p1,p2),function(x)x$labels$shape)

[[1]] [1]“BetaAdjusted”

[[2]] [1]“Beta调整?”

答案 2 :(得分:0)

从p2中提取信息更容易:

> p2$labels$shape
#[1] "Is Beta Adjusted?"

而在p1中,文本&#34; Beta是否已调整?&#34;是&#34;隐藏&#34;在p1 $ scale:

> p1$scales
#Reference class object of class "Scales"
#Field "scales":
#[[1]]
#discrete_scale(aesthetics = "shape", scale_name = "shape_d", 
#    palette = shape_pal(solid), name = "Is Beta Adjusted?")

或者,如果准确的文字是'β调整?&#34;不需要,您可以对p1和p2使用相同的语法:

> p1$labels$shape
#[1] "BetaAdjusted"
> p2$labels$shape
#[1] "Is Beta Adjusted?"
相关问题