Matplotlib图表X轴刻度标签未全部显示且位置异常的问题排查与解决咨询
Fixing Missing/ Misaligned X-Tick Labels in Matplotlib Dual-Axis Chart
I get it—dealing with wonky tick labels in dual-axis plots can be frustrating. Let’s break down what’s going wrong and fix it step by step:
Key Issues & Fixes
- Missing labels: You’re setting tick labels without first defining exactly where the ticks should go. Matplotlib defaults to sparse ticks if you don’t specify positions, so only a subset of your defect names get displayed.
- Misaligned positions: Without explicit tick positions, labels end up offset from their corresponding bars. We need to lock ticks to every row in your DataFrame.
- Label clipping/ mess: Rotating labels helps, but adding right alignment will keep them neat and prevent them from getting cut off by the figure edge.
Updated Working Code
Here’s your revised code with all fixes applied:
import matplotlib.pyplot as plt from matplotlib.ticker import PercentFormatter fig, ax1 = plt.subplots() fig.set_figheight(7) fig.set_figwidth(12) # Bar plot on primary axis ax1.bar(df.index, df['occurence of defects'], color="C0") ax1.set_ylabel("Qty", color="C0") ax1.tick_params(axis="y", colors="C0") ax1.set_xlabel("Defect") # Critical fix: Define tick positions first, then labels with alignment ax1.set_xticks(df.index) # Ensures one tick per defect in your DataFrame ax1.set_xticklabels(df['Name of Defect'], rotation=45, ha='right') # Right-align rotated labels for readability # Line plot on secondary axis ax2 = ax1.twinx() ax2.plot(df.index, df["cum percentage"], color="C1", marker="D", ms=7) ax2.yaxis.set_major_formatter(PercentFormatter()) ax2.tick_params(axis="y", colors="C1") # Optional but helpful: Auto-adjust margins to avoid label clipping plt.tight_layout() plt.show()
What Changed?
ax1.set_xticks(df.index): This forces Matplotlib to place a tick at every index position in your DataFrame, so every defect name gets a corresponding label.ha='right'inset_xticklabels(): Rotated labels now align to the right edge of their tick, making them look clean and centered above each bar.plt.tight_layout(): This automatically adjusts the plot’s margins to ensure all rotated labels fit without getting cut off.
After these changes, all your X-axis labels should be visible, perfectly aligned with their bars, and easy to read!
内容的提问来源于stack exchange,提问作者user18013381
相关产品推荐
相关产品推荐

