如何缩小ggplot坐标轴文本行之间的间距?
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

