You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在ggplot2中实现多行文本两端对齐?含标题、geom_text等场景

在ggplot2中实现多行文本两端对齐

需求概述

需要在ggplot2中实现多行文本两端对齐:通过调整单词间距,让每行文本左右两端都与边距对齐,仅段落最后一行保持左对齐。适用场景包括图表标题、副标题、说明文字,以及通过geom_text()添加的注释文本。

常规方法的局限

使用ggplot2原生功能或ggtext包时,仅能通过hjust(ggtext中为halign)参数实现左、中、右对齐,无法达成两端对齐的效果。

解决方案:使用marquee包

借助marquee包可以实现该需求,不过需要手动指定文本的固定宽度。示例代码如下:

library(marquee)
library(tidyverse)

# 测试文本
my_text <- 
  "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
# 重复文本生成副标题内容
my_subtitle <- paste(rep(my_text, 5), collapse = " ")

# 构建用于geom_marquee的数据框
df <- tibble(
  my_text = rep(my_text, 3),
  x = c(1, 2, 3),
  y = c(2, 1, 0),
  hjust = c(0, 0.5, 1),
  vjust = c(0, 0.5, 1)
)

ggplot() +
  ggtitle("marquee::geom_marquee() 和 marquee::element_marquee()") +
  # 用geom_marquee实现注释文本的两端对齐
  marquee::geom_marquee(
    data = df,
    aes(
      x = vjust,
      y = hjust,
      hjust = hjust,
      vjust = vjust,
      label = my_text
    ),
    width = unit(6, "cm"), # 需要手动设置固定宽度
    style = marquee::classic_style(align = "justified-left")
  ) +
  labs(subtitle = my_subtitle) +
  # 用element_marquee实现副标题的两端对齐
  theme(plot.subtitle = marquee::element_marquee(
    hjust = 0,
    width = unit(20, "cm"), # 需要手动设置固定宽度
    style = marquee::classic_style(align = "justified-left")
  ))

内容的提问来源于stack exchange,提问作者Paul Schmidt

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 22:09:15