如何在expression()中包含带有已保存文本的对象以用于ggplot2图形?

时间:2018-09-04 01:25:34

标签: r ggplot2 expression

我正在尝试将数学符号和对象与保存到它们的值组合起来,以使用geom_text()在ggplot图形中显示。这是与我的问题有关的示例代码:

# values 
diff <- "0.81"
p <- "p < .01"

# approach 1) pasting in values
temp <- data.frame(condition = c("first"), value = c(2)) %>%
  mutate(test = as.character(expression(atop(beta["2"] - beta["1"] == "-0.80", "p < 0.01")))) 

ggplot() +
      geom_bar(data = temp, aes(x = condition, y = value), stat = "identity") +
      ylim(0, 5) +
      geom_text(data = temp, x = 1, y = 4, aes(label = test), size = 7, parse = TRUE) 

# approach 2) referring to objects with values
temp <- data.frame(condition = c("first"), value = c(2)) %>%
  mutate(test = as.character(expression(atop(beta["2"] - beta["1"] == diff, p))))

ggplot() +
  geom_bar(data = temp, aes(x = condition, y = value), stat = "identity") +
  ylim(0, 5) +
  geom_text(data = temp, x = 1, y = 4, aes(label = test), size = 7, parse = TRUE) 

方法1创建了我想要的图形,但是我希望能够轻松地引用对象以提供在beta之后出现的值。如果我采用当前方法2,则不会使用保存到对象的值,而只会使用文本“ diff”和“ p”。有没有一种方法可以维护方法1的基本结构,但是可以使用对象来创建我想要的图形?

1 个答案:

答案 0 :(得分:1)

我不确定在有更多行时究竟要发生什么,但是如果要部分扩展某些变量,我认为使用bquote最简单。我将其提取到函数中是因为要对其进行正确的向量化可能有些棘手

mylabs <- function(diff, p) {
  sapply(mapply(function(diff, p) bquote(atop(beta["2"] - beta["1"] == .(diff), .(p))), diff, p), deparse)
}

temp <- data.frame(condition = c("first"), value = c(2)) %>%
  mutate(test = mylabs(diff, p))