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

如何换行带有上标的ggplot图例标题

解决ggplot图例标题带上下标并换行的问题

你之前用\n没生效是因为element_markdown()遵循Markdown语法,单纯的\n不会触发换行,得用Markdown的换行标签<br>;而bquote(atop())是base绘图的表达式语法,和ggtext的Markdown渲染不兼容,所以一起用没效果。

直接用Markdown语法写标题内容就行,把换行处换成<br>,同时保留<sup>做上标,代码如下:

library(tidyverse)
library(ggtext)
library(ggplot2)

ggplot(mtcars, aes(x = disp, y = hp, fill = hp, size = mpg)) +
  geom_point(shape = 21) +
  scale_fill_gradient2(low = "blue", high = "red",
                       midpoint = mean(mtcars$hp),
                       name = 'Air Temperature<br>Trend (<sup>o</sup>C yr<sup>-1</sup>)') +
  scale_size_continuous(name = 'Air Temperature<br>Trend (<sup>o</sup>C yr<sup>-1</sup>)') +
  theme(legend.title = element_markdown())

这样就能在Temperature后换行,同时正确显示上标。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 09:15:29