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

使用Pandas绘制柱状图时X轴显示混乱,求解决方法

Fixing Messy X-Axis Labels in Pandas Bar Plots

Hey there! I get it—rotating X-axis labels 90 degrees should help, but sometimes things still look cramped or jumbled. Let's fix that with a few targeted adjustments to your code.

First, let's recap your original code for context:

ax = yearresult.plot(kind='bar', x='BBB', y='AAA')
ax.set_xticklabels(ax.get_xticklabels(), rotation=90)
ax.legend(["AAA", "BBB"])
plt.tight_layout()
plt.show()

Here are the most common fixes for your issue:

  • Let Pandas handle rotation directly (avoid manual label reset)
    Sometimes manually calling set_xticklabels can cause misalignment or duplicate label rendering. Instead, pass the rotation directly to Pandas' plot method, and shrink the font size to prevent overcrowding:

    ax = yearresult.plot(kind='bar', x='BBB', y='AAA', rot=90, fontsize=8)
    ax.legend(["AAA", "BBB"])
    plt.tight_layout()
    plt.show()
    

    Adjust the fontsize value (try 6-10) based on how long your labels are.

  • Add extra bottom padding for rotated labels
    tight_layout works well, but rotated labels often need more space at the bottom to avoid getting cut off or overlapping. Use subplots_adjust to tweak this:

    ax = yearresult.plot(kind='bar', x='BBB', y='AAA', rot=90)
    ax.legend(["AAA", "BBB"])
    plt.subplots_adjust(bottom=0.3)  # Increase this value if labels are still cut off
    plt.tight_layout()
    plt.show()
    
  • Truncate or wrap long labels
    If your BBB column has very long strings, even rotation won't fix the clutter. Try truncating labels or adding line breaks:

    ax = yearresult.plot(kind='bar', x='BBB', y='AAA', rot=90)
    # Truncate labels to first 10 characters + ellipsis
    truncated_labels = [label.get_text()[:10] + '...' for label in ax.get_xticklabels()]
    ax.set_xticklabels(truncated_labels, fontsize=8)
    ax.legend(["AAA", "BBB"])
    plt.tight_layout()
    plt.show()
    

    For wrapping, you could replace spaces with \n in your labels before plotting, or use a helper function to split long strings into lines.

  • Check for duplicate X-axis categories
    If your yearresult DataFrame has duplicate values in the BBB column, that can cause overlapping labels. Double-check your data with yearresult['BBB'].nunique() to ensure you're plotting unique categories.

Start with the first two tweaks—they're the quickest fixes for most cases!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 07:37:47