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

解决ggplot2绘制柱状图时X轴标签重叠问题

解决ggplot2柱状图X轴标签重叠的几种方法

以下是几个实用的解决思路,直接修改你的代码就能生效:

  • 旋转X轴标签
    把标签旋转一定角度,避免横向拥挤,同时调整对齐方式提升可读性:

    library(ggplot2)
    
    ggplot(data,aes(State,Confirmed))+
        geom_bar(stat = "identity")+
        theme(axis.text.x = element_text(angle = 45, hjust = 1)) # 旋转45度并右对齐
    
  • 缩小标签字体
    如果标签内容不算太长,直接缩小字体大小就能解决重叠:

    library(ggplot2)
    
    ggplot(data,aes(State,Confirmed))+
        geom_bar(stat = "identity")+
        theme(axis.text.x = element_text(size = 8)) # 将字体大小设为8号
    
  • 分面拆分展示
    当X轴类别特别多时,把图表拆分成多个小面板分散展示:

    library(ggplot2)
    
    ggplot(data,aes(State,Confirmed))+
        geom_bar(stat = "identity")+
        facet_wrap(~State, scales = "free_x", ncol = 5) # 按State分面,每行放5个面板
    
  • 标签换行+调宽图表
    若想保留横向标签,可给长标签手动换行,再配合调整图表宽度:

    library(ggplot2)
    library(stringr)
    
    # 给State标签添加换行符,比如每5个字符换一行
    data$State <- str_wrap(data$State, width = 5)
    
    ggplot(data,aes(State,Confirmed))+
        geom_bar(stat = "identity")+
        theme(repr.plot.width = 12) # 适当调宽图表
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 05:33:16