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

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?

  1. 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.
  2. ha='right' in set_xticklabels(): Rotated labels now align to the right edge of their tick, making them look clean and centered above each bar.
  3. 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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.28 14:22:36