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

如何在ggplot2中实现X轴文本换行或拉长图表以提升可读性?

解决ggplot2 X轴文本拥挤的两种实用方法

一、X轴文本自动换行

通过以下两种方式实现文本换行,避免拥挤重叠:

  • 方式1:修改原始数据的分类文本
    使用stringr包的str_wrap函数,按指定宽度自动给X轴分类文本插入换行符(宽度数值可根据文本实际长度调整):
library(stringr)
bureau_status_df3$Var2 <- str_wrap(bureau_status_df3$Var2, width = 10)
  • 方式2:在绘图代码中直接处理X轴(不修改原始数据)
    直接在aes的x参数里调用str_wrap,无需改动原始数据框:
ggplot(bureau_status_df3, aes(fill=Var1, y=Freq, x=str_wrap(Var2, width = 10))) + 
  # 后续绘图代码不变

配合调整文本角度和对齐,可读性更强:
在theme中添加以下设置,让倾斜的文本避免与图表主体重叠:

theme(axis.text.x = element_text(angle = 45, hjust = 1))

二、拉长图表尺寸

通过ggsave保存图表时指定更大的宽度,给X轴预留足够展示空间:

# 宽度设为12英寸(可按需调整),高度适配即可
ggsave("status_plot.png", width = 12, height = 6, dpi = 300)

完整示例代码

library(ggplot2)
library(stringr)

ggplot(bureau_status_df3, aes(fill=Var1, y=Freq, x=str_wrap(Var2, width = 10))) + 
  geom_bar(position='fill', stat='identity') + 
  scale_fill_hue(h = c(100, 420)) +
  ggtitle("Status by Violation Bureau") + 
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 45, hjust = 1))

# 保存宽幅图表
ggsave("status_plot.png", width = 12, height = 6, dpi = 300)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:12:48