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

Posted

技术标签:

【中文标题】在ggplot中,如何在左对齐的同时将文本定位在最右端?【英文标题】:In ggplot, how to position a text at the very right end while having it left-aligned? 【发布时间】:2021-11-07 18:42:08 【问题描述】:

我正在尝试使用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 创建


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

无论图像是否重新缩放,都会向右刷新(例如,x = Inf) 左对齐

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


我的失败尝试

首先,我用 label 列补充我的 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 所做的那样)同时左对齐?

【问题讨论】:

【参考方案1】:

我相信 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 创建

【讨论】:

以上是关于在ggplot中,如何在左对齐的同时将文本定位在最右端?的主要内容,如果未能解决你的问题,请参考以下文章

如何在ggplot2中对齐旋转的多行x轴文本?

如何在ggplot2的注释中左对齐文本

如何在ggplot2中移动或定位图例

如何在单个ggplot2中对齐图层(密度图和垂直线)

如何在布局中保持统一对齐

ggplot:如何根据变量类型在 geom_text 位置上设置不同的对齐方式?