如何将带有变量的格式化文本添加到多面包装的 ggplot 中?

How do I add formatted text with a variable to a ggplot that is facet wrapped?

我正在尝试弄清楚如何为每个子图添加一个不错的 R^2 = 值。

现在我可以在图中添加我想要的值(来自单独的数据框),但我不知道如何在它前面添加一个斜体和上标的“R^2 =”。

任何建议表示赞赏。感谢您的宝贵时间!

example_df <- data.frame(x = c(1,2,5,7,8,9,10),
                         y = c(1,3,5,7,8, 9, 10),
                         grp = c("a", "a", "b","b","b", "c", "c"))

grp_info <- data.frame( grp = c("a", "b", "c"),
                        num = c(0.5, 0.75, 1))
  
plt <- ggplot(example_df, aes(x = x, y=y, group = grp)) +
  geom_point() + 
  facet_wrap(vars(grp), ncol = 2, scales = "free")+
  annotate(geom = "text", x = -Inf, y = Inf, label = grp_info$num, hjust = 0, vjust =1)

print(plt)

如果我只想很好地格式化“R^2 =”,则可以使用以下方法,但它不允许我从单独的数据框中添加值。

plt <- ggplot(example_df, aes(x = x, y=y, group = grp)) +
  geom_point() + 
  facet_wrap(vars(grp), ncol = 2, scales = "free")+
  annotate(geom = "text", x = -Inf, y = Inf, label = paste("paste(italic(R) ^ 2,\"=\")"), parse = TRUE, hjust = 0, vjust =1)

我在评论中迟来提出的最后一点是,理想情况下,这种添加应该是多行的,允许添加另一个变量表达式。

我认为最好将您的注释分配为 geom_text 调用 - 这在某些方面与 annotate 的作用相同,但会与您的 [=13= 保持同步] 通话:

library(ggplot2)

example_df <- data.frame(
  x = c(1, 2, 5, 7, 8, 9, 10),
  y = c(1, 3, 5, 7, 8, 9, 10),
  grp = c("a", "a", "b", "b", "b", "c", "c")
)

grp_info <- data.frame(grp = c("a", "b", "c"),
                       num = c(0.5, 0.75, 1))

ggplot(example_df, aes(x = x, y = y, group = grp)) +
  geom_point() +
  facet_wrap(vars(grp), ncol = 2, scales = "free") +
  geom_text(
    data = grp_info,
    aes(
      x = -Inf,
      y = Inf,
      label = paste0("italic(R)^2", "==", num)
    ),
    parse = TRUE,
    hjust = 0,
    vjust = 1
  )

reprex package (v1.0.0)

于 2021-03-24 创建

您可以使用 plotmath::atop 描述的 here 在解析的表达式中获取换行符。这是一个相当混乱的结构,但它确实有效。这是一个例子:

library(tidyverse)

example_df <- data.frame(
  x = c(1, 2, 5, 7, 8, 9, 10),
  y = c(1, 3, 5, 7, 8, 9, 10),
  grp = c("a", "a", "b", "b", "b", "c", "c")
)

grp_info <- data.frame(grp = c("a", "b", "c"),
                       num = c(0.5, 0.75, 1),
                       rmse = c(4, 5, 6))

ggplot(example_df, aes(x = x, y = y, group = grp)) +
  geom_point() +
  facet_wrap(vars(grp), ncol = 2, scales = "free") +
  geom_text(
    data = grp_info,
    aes(
      x = -Inf,
      y = Inf,
      label = paste0("atop(", "italic(R)^2", "==", num,",", "RMSE", "==", rmse, ")")
    ),
    parse = TRUE,
    hjust = 0,
    vjust = 1
  )

reprex package (v1.0.0)

于 2021 年 3 月 25 日创建