使用Pandas绘制柱状图时X轴显示混乱,求解决方法
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 callingset_xticklabelscan cause misalignment or duplicate label rendering. Instead, pass the rotation directly to Pandas'plotmethod, 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
fontsizevalue (try 6-10) based on how long your labels are.Add extra bottom padding for rotated labels
tight_layoutworks well, but rotated labels often need more space at the bottom to avoid getting cut off or overlapping. Usesubplots_adjustto 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 yourBBBcolumn 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
\nin your labels before plotting, or use a helper function to split long strings into lines.Check for duplicate X-axis categories
If youryearresultDataFrame has duplicate values in theBBBcolumn, that can cause overlapping labels. Double-check your data withyearresult['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

