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

Matplotlib图表X轴标签重叠问题如何解决?

解决Matplotlib图表X轴标签重叠且角度无法修改的问题

你的问题出在使用twinx()创建双轴后,plt.xticks(rotation=45)没有作用到承载X轴的主坐标轴ax1上,导致标签角度没变化,重叠问题也没解决。以下是具体修复方案:

核心修复:针对主坐标轴设置X轴标签属性

把原来的plt.xticks(rotation=45)替换成对ax1的直接设置,同时添加标签对齐优化,避免旋转后标签偏移:

# Create a figure with sharing x-axis
fig, ax1 = plt.subplots(figsize=(10, 6))

# weekly order count on the left y-axis
ax1.bar(weekly_order_count.index.astype(str), weekly_order_count['id_order'], label='Weekly Order Count', color='skyblue')
ax1.set_ylabel('Order Count', color='skyblue')
ax1.tick_params('y', colors='skyblue')
# 直接在ax1上设置X轴标签旋转和右对齐
ax1.set_xticklabels(weekly_order_count.index.astype(str), rotation=45, ha='right')

# second y-axis for the discount rate on the right side
ax2 = ax1.twinx()
ax2.plot(weekly_discount_rate.index.astype(str), weekly_discount_rate['disc_pct'], label='Weekly Discount Rate', color='orange', marker='o', linestyle='--')
ax2.set_ylabel('Discount Rate (%)', color='orange')
ax2.tick_params('y', colors='orange')

# titles and labels
plt.title('Comparison of Weekly Order Count and Weekly Discount Rate')
plt.xlabel('Week')
lines, labels = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc='upper left')
# 调整子图间距,防止标签被截断
plt.tight_layout()
plt.show()

额外优化方案

如果旋转后仍存在重叠,可尝试以下方法:

  • 缩小X轴标签字体:在ax1.set_xticklabels中添加fontsize=8参数
  • 用自动旋转对齐功能:替换为ax1.tick_params(axis='x', rotation=45, ha='right')
  • 增大图表宽度:把figsize=(10,6)调整为figsize=(12,6)
  • 跳过部分标签:若周数过多,可每隔一个显示一个标签,比如ax1.set_xticks(ax1.get_xticks()[::2])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 14:59:55