ggplot如何设置第一行居中、后续行左对齐的多行caption
要实现ggplot caption首行居中、其余行左对齐的效果,需要借助ggtext包的富文本支持能力,原生ggplot的caption仅支持全局统一对齐规则,无法单独为不同行设置对齐属性。
具体实现步骤
- 先安装
ggtext包(已安装可跳过)
install.packages("ggtext")
- 调整代码,使用HTML标签控制各行对齐规则,同时在theme中开启富文本解析
library(ggplot2) library(ggtext) ggplot(data = iris, aes(x = Sepal.Length, y = Sepal.Width, color = Species)) + geom_point() + geom_line() + ylab("HHI") + labs(caption = "<center>*Source:* By author's calculation</center> Two extreme cases would have something blabla equal to 10,000 and 0, respectively.") + theme( plot.caption = element_markdown(hjust = 0) )
代码说明
- 用
<center>标签包裹第一行内容,即可实现单独将首行居中的效果,剩余行不受影响默认左对齐 - 原
expression中的斜体效果直接用markdown的*包裹即可实现,无需复杂的表达式写法 theme中设置plot.caption = element_markdown()是为了让ggplot识别并解析caption中的html、markdown标签,hjust = 0保证整个caption块的左边缘对齐绘图区域的左边缘,避免整体偏移。
你原代码运行后不符合预期的效果图如下:
内容的提问来源于stack exchange,提问作者jck21
相关产品推荐
相关产品推荐

