首页 > 解决方案 > 如何将带有变量的格式化文本添加到分面包装的 ggplot?

问题描述

我试图弄清楚如何为每个子图添加一个不错的 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)

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

标签: rggplot2formattinglabelfacet-wrap

解决方案


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

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 包于 2021-03-24 创建(v1.0.0)


推荐阅读