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

如何在ggplot2中实现换行后的坐标轴标题居中对齐?

ggplot2实现带科学符号的y轴标题换行+居中对齐

要解决这个问题,核心在于保留表达式(expression)的科学符号格式,同时实现换行和居中。之前的方法要么破坏了表达式格式,要么没设置正确的对齐参数,下面是两种可行方案:

方案1:用atop()构建自动居中的换行表达式

atop()是R的数学表达式语法,专门用于创建多行上下对齐文本,默认居中,完美适配带科学符号的标题需求。

library(ggplot2)
set.seed(321)
df <- data.frame(matrix(ncol = 2, nrow = 3))
colnames(df)[1:2] <- c("date","value")
df$value <- round(rnorm(3, 100,30),0)
st <- as.Date("2020-01-01")
en <- as.Date("2020-03-31")
df$date <- seq.Date(st,en,by = '1 month')

ggplot(df, aes(x = date, y = value)) +
  geom_point() +
  labs(x = "",
       # 用atop拆分两行,~用于添加合理空格
       y = expression(atop("Here is a really really really", 
                           "looooonnnng title with notation ("~m^-2~")"))) +
  scale_x_date(breaks = seq(st, en, by = "1 month"),
               limits = c(st,en),
               date_labels = "%b %Y") +
  scale_y_continuous(limits = c(0,150),
                     breaks=seq(0,150,25)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 14, color = "black", angle = 90, vjust = 0.5, hjust = 1),
        axis.text.y = element_text(size = 14, color = "black"))

方案2:手动\n换行+主题设置居中对齐

如果习惯用\n手动控制换行位置,只需在theme里给axis.title.y设置hjust = 0.5即可实现居中,同时保留表达式格式。

library(ggplot2)
set.seed(321)
df <- data.frame(matrix(ncol = 2, nrow = 3))
colnames(df)[1:2] <- c("date","value")
df$value <- round(rnorm(3, 100,30),0)
st <- as.Date("2020-01-01")
en <- as.Date("2020-03-31")
df$date <- seq.Date(st,en,by = '1 month')

ggplot(df, aes(x = date, y = value)) +
  geom_point() +
  labs(x = "",
       y = expression(paste("Here is a really really really\n", 
                           "looooonnnng title with notation ("~m^-2~")"))) +
  scale_x_date(breaks = seq(st, en, by = "1 month"),
               limits = c(st,en),
               date_labels = "%b %Y") +
  scale_y_continuous(limits = c(0,150),
                     breaks=seq(0,150,25)) +
  theme_bw() +
  theme(panel.grid = element_blank(),
        text = element_text(size = 16),
        axis.text.x = element_text(size = 14, color = "black", angle = 90, vjust = 0.5, hjust = 1),
        axis.text.y = element_text(size = 14, color = "black"),
        # 关键:设置y轴标题水平居中
        axis.title.y = element_text(hjust = 0.5))

为什么之前的方法失效?

  • str_wrap()或自定义包装函数:这类函数会把expression对象强制转为普通字符串,直接丢失科学符号的上标格式。
  • 仅用\n换行未设置hjust:ggplot2中表达式类型的轴标题默认左对齐,必须手动设置hjust = 0.5才能触发居中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:54:26