在 ggplot 中,如何在左对齐的同时将文本定位在最右端?

In ggplot, how to position a text at the very right end while having it left-aligned?

我正在尝试使用 ggplot()geom_text() 创建一个图,以便在图的最右端添加文本注释,但文本仍然左对齐。我尝试了很多x定位和hjust的组合,但到目前为止都无济于事。

例子

让我们根据 ToothGrowth 内置数据集创建一个箱线图。在初始阶段,我希望每个方面都有一个geom_hline() mean 如下:

library(ggplot2)

mean_per_panel <- aggregate(len ~ supp, data = ToothGrowth, FUN = mean)

p <- 
  ggplot(ToothGrowth, aes(x = factor(dose), y = len)) +
  geom_boxplot() +
  geom_hline(data = mean_per_panel, 
             aes(yintercept = len, group = "supp"), 
             linetype = 2, 
             color = "red") +
  facet_wrap(~supp) +
  theme_bw()

p

reprex package (v2.0.0)

于 2021-09-11 创建

到目前为止一切顺利。问题来了:我想添加一些注释来解释虚线。我希望这样的文字是:

所以期望的输出应该是这样的:


我失败的尝试

首先,我用 标签 列补充我的 mean_per_panel 数据摘要:

library(dplyr, warn.conflicts = FALSE)

mean_per_panel_with_label <-
  mean_per_panel %>%
  mutate(my_label = paste("mean for", supp, "is:", round(len, 2), sep = "\n"))

mean_per_panel_with_label
#>   supp      len                 my_label
#> 1   OJ 20.66333 mean for\nOJ\nis:\n20.66
#> 2   VC 16.96333 mean for\nVC\nis:\n16.96

以下是实现所需输出的一些尝试,但均未成功:

my_geom_text <- function(x_pos, ...) {
  geom_text(data = mean_per_panel_with_label, 
            aes(y = len, label = my_label),
            vjust = 1,
            x = x_pos,
            ...,
            color = "red") 
}

p +
  my_geom_text(x_pos = 2, hjust = 0)

p +
  my_geom_text(x_pos = 2.8, hjust = 0)

p +
  my_geom_text(x_pos = Inf, hjust = 1)

p +
  my_geom_text(x_pos = Inf, hjust = 1.2)

reprex package (v2.0.0)

于 2021-09-11 创建

有没有办法让文本显示在最右边总是(就像x = Inf所做的那样)并同时左对齐?

我相信 ggtext 的 geom_textbox() 可以满足您的需求。 In 引入了 hjusthalign 的分离来单独对齐框和文本。

library(ggtext)
library(ggplot2)
library(dplyr)

mean_per_panel <- ToothGrowth %>%
  group_by(supp) %>%
  summarise(mean = mean(len)) %>%
  mutate(my_label = paste("mean for", supp, "is:", round(mean, 2), sep = "<br>"))

ggplot(ToothGrowth, aes(as.factor(dose), len)) +
  geom_boxplot() +
  geom_hline(data = mean_per_panel, aes(yintercept = mean),
             colour = "red") +
  geom_textbox(
    data = mean_per_panel,
    aes(y = mean, x = Inf, label = my_label),
    hjust = 1, halign = 0, 
    box.colour = NA, fill = NA, # Hide the box fill and outline
    box.padding = unit(rep(2.75, 4), "pt"), colour = "red",
    vjust = 1, width = NULL
  ) +
  facet_grid(~ supp)

reprex package (v2.0.1)

于 2021-09-11 创建