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

如何缩小ggplot坐标轴文本行之间的间距?

Fixing Excessive Line Spacing for Multi-Line Axis Titles in ggplot2

Got it, let's tackle that oversized line spacing in your axis titles! Since you're using element_markdown (which is perfect for styled multi-line text), there are two simple, effective ways to tighten up those lines:

1. Adjust the lineheight parameter in element_markdown

You can directly add a lineheight argument to your axis.title.x and axis.title.y theme elements. Values less than 1 will reduce the spacing between lines—start with 0.8 or 0.9 and tweak to match your presentation needs.

Here's how to update your theme code:

theme( 
  plot.background = element_rect(fill = "white",colour = NA), 
  panel.background = element_rect(fill = 'white', colour = 'white'), 
  panel.border = element_blank(), 
  legend.position = "none", 
  plot.title = element_markdown(hjust = 0.5, family = "title", size = 45), 
  plot.subtitle = element_markdown(hjust = 0.5, family = "subtitle", size = 30), 
  axis.title.x = element_markdown(hjust = 0.5, family = "subtitle", size = 33, lineheight = 0.8), # Added lineheight
  axis.text.x = element_markdown(hjust = 0.5, family = "subtitle", size = 20), 
  axis.title.y = element_markdown(hjust = 0.5, family = "subtitle", size = 33, lineheight = 0.8), # Added lineheight
  axis.text.y = element_markdown(hjust = 0.5, family = "subtitle", size = 20), 
  plot.caption = element_text(hjust = 0, size = 21, family = "caption")) 

2. Use inline CSS line-height styling

If you want more granular control, wrap your axis title text in a <span> tag with an explicit line-height style. This works because element_markdown parses HTML/CSS:

Update your labs() section like this:

labs(title = "<span style = 'color:#005A9C;'>A vs. B</span>", 
     x = "<span style='line-height:0.8;'>B<br>BBBBB<br>BBBBBBBBBB<br>BBBBBBBBBB</span>", 
     y = "<span style='line-height:0.8;'>A<br>AAAAA<br>AAAAAAAAAA<br>AAAAAAAAAA</span>", 
     caption = expression(paste(italic("Source:"), " JJJJJ")))

Either method will shrink the gap between your multi-line axis titles. I usually start with the lineheight parameter in element_markdown since it keeps your theme code consistent, but both work great for presentation-ready plots!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.27 14:27:46