【问题标题】:How to add expressions to labels in facet_wrap? [duplicate]如何将表达式添加到 facet_wrap 中的标签? [复制]
【发布时间】:2013-10-09 21:15:50
【问题描述】:

我有一个数据集,我想从中绘制小的倍数,特别是在 2×2 数组中,如下所示:

mydf <- data.frame(letter = factor(rep(c("A", "B", "C", "D"), each = 20)), x = rnorm(80), y = rnorm(80))
ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_wrap(~ letter, ncol = 2)

但是,我希望每个构面标签都包含一个表达式,例如

expression(paste("A or ", alpha))

我可以通过使用facet_grid() 来实现这一点

f_names <- list('A' = expression(paste("A or ", alpha)), 'B' = expression(paste("B or ", beta)), 'C' = expression(paste("C or ", gamma)), 'D' = expression(paste("D or ", delta)))
f_labeller <- function(variable, value){return(f_names[value])}
ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_grid(~ letter, labeller = f_labeller)

但后来我丢失了 2×2 数组。如何使用表达式重命名 facet_wrap() 构面标签?或者,我如何通过使用facet_grid() 重新创建 2×2 数组来解决这个问题,但只能通过单个变量进行刻面?

(这个问题建立在@baptiste 对this previous question 的回答中的括号内。)

谢谢!

【问题讨论】:

  • @baptiste:是的!谢谢,您链接到的问答中的facet_wrap_labeller() 功能效果很好。 @Ricardo:感谢那个链接——我找到了那个答案,它最初把我推向了这个问题。谢谢你们。

标签: r ggplot2


【解决方案1】:

为了按照我的要求进行操作,首先从@Roland 加载这个贴标功能,首先出现在here

facet_wrap_labeller <- function(gg.plot,labels=NULL) {
  #works with R 3.0.1 and ggplot2 0.9.3.1
  require(gridExtra)

  g <- ggplotGrob(gg.plot)
  gg <- g$grobs      
  strips <- grep("strip_t", names(gg))

  for(ii in seq_along(labels))  {
    modgrob <- getGrob(gg[[strips[ii]]], "strip.text", 
                       grep=TRUE, global=TRUE)
    gg[[strips[ii]]]$children[[modgrob$name]] <- editGrob(modgrob,label=labels[ii])
  }

  g$grobs <- gg
  class(g) = c("arrange", "ggplot",class(g)) 
  g
}

然后保存原来的ggplot()对象:

myplot <- ggplot(mydf, aes(x = x, y = y)) + geom_smooth(method = "lm") + geom_point() + facet_wrap(~ letter, ncol = 2)

然后调用facet_wrap_labeller() 并将表达式标签作为参数提供:

facet_wrap_labeller(myplot, labels = c(expression(paste("A or ", alpha)), expression(beta), expression(gamma), expression(delta)))

表达式现在应显示为facet_wrap() 标签。

【讨论】:

  • 更简单的使用方法,不需要在标签的每个字段上传递表达式,“标签”也不需要: facet_wrap_labeller(myplot, expression(paste("A or ", alpha), beta , 伽马, delta))
  • 对于目前尝试此操作的任何人,ggplot 中的解决方案现已实施。 ggplot index 底部有一个很好的示例,它展示了如何使用 facet_wrap 轻松完成此操作。
猜你喜欢
  • 2019-08-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 2016-09-24
  • 2021-07-31
相关资源
最近更新 更多