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

使用ggpubr的ggline函数绘图如何避免X轴长标签重叠

ggline X轴长标签重叠解决方法

问题说明

你使用的7个阿姆斯特丹区域名称字符长度较长,ggplot2默认的横向标签排版无法容纳,就会出现重叠。另外注意原有代码的xlab和ylab设置颠倒了:x轴对应区域分类,y轴对应价格差值,参数需要对应调整。

方案1:旋转X轴标签(最常用)

通过theme()调整X轴文字的旋转角度和对齐方式,通常旋转45度即可解决重叠问题,保存PDF时调整宽度避免标签被截断:

library(ggpubr)
# 旋转45度方案
p <- ggline(only_price_district, x = "neighbourhood_cleansed", y = "price_difference",
       add = c("mean_se", "jitter"),
       ylab = "Price difference", xlab = "District") + # 修正了原代码的坐标轴标注颠倒问题
  theme(axis.text.x = element_text(angle = 45, hjust = 1)) # angle为旋转角度,hjust=1保证标签末尾对齐坐标轴刻度

# 保存pdf时调整宽高适配内容
ggsave("district_price.pdf", p, width = 10, height = 6)

如果旋转45度仍有重叠,可将角度改为90度:axis.text.x = element_text(angle = 90, hjust = 1, vjust = 0.5)

方案2:自动换行X轴标签

提前把区域名称里的下划线替换为换行符,缩短单个标签的横向宽度:

library(dplyr)
library(ggpubr)

# 替换下划线为换行符
only_price_district <- only_price_district %>%
  mutate(neighbourhood_cleansed = gsub("_", "\n", neighbourhood_cleansed))

p <- ggline(only_price_district, x = "neighbourhood_cleansed", y = "price_difference",
       add = c("mean_se", "jitter"),
       ylab = "Price difference", xlab = "District")

ggsave("district_price_wrap.pdf", p, width = 9, height = 7)

方案3:坐标轴翻转(适配极长标签)

直接互换X轴和Y轴,用横向布局完全避免长标签重叠:

p <- ggline(only_price_district, x = "neighbourhood_cleansed", y = "price_difference",
       add = c("mean_se", "jitter"),
       ylab = "Price difference", xlab = "District") +
  coord_flip() # 坐标轴翻转函数

ggsave("district_price_flip.pdf", p, width = 8, height = 7)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 13:36:03