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

Matplotlib使用ax.twinx()时仅保留一组X轴刻度的问题

问题:双轴绘图添加高时间分辨率数据后X轴刻度过于密集

我使用ax.twinx()在同一绘图中展示两个DataFrame的数据,第一次绘图(数据时间分辨率为1小时)显示正常,但添加时间分辨率为10分钟的第二个数据后,X轴会显示每个时间点的刻度,导致刻度过于密集无法正常查看。尝试了多种相关命令均未解决,寻求有效解决方案。

第一次正常绘图代码

figi, ax1=plt.subplots()
ax1.plot(locals()[edfn].datetime, locals()[edfn].ic_mean, label='ic mean')
ax2=ax1.twinx()
ax1.legend(title='gauge name', loc='upper left')
ax1.set_ylabel('Rain (mm)', rotation=90)
ax1.set_xlabel('Datetime')
ax1.tick_params(axis='x',rotation=90)
#for xx in gl2:
ax2.plot(locals()[dfn]['datetime'], locals()[dfn][xx]*100, label=xx)
# mfmt=mds.DateFormatter('%m-%d-%H')
# ax1.xaxis.set_major_formatter(mfmt)
# ax1.xaxis.set_(interval=1)
#ax2.tick_params(axis='x', which='both', bottom=False)
#ax2.tick_params(labelbottom=False)
#plt.setp(ax2.get_xticklabels(),visible=False)
figi.tight_layout()

添加高分辨率数据后出问题的代码

figi, ax1=plt.subplots()
ax1.plot(locals()[edfn].datetime, locals()[edfn].ic_mean, label='ic mean')
ax2=ax1.twinx()
ax1.legend(title='gauge name', loc='upper left')
ax1.set_ylabel('Rain (mm)', rotation=90)
ax1.set_xlabel('Datetime')
ax1.tick_params(axis='x',rotation=90)
#for xx in gl2:
ax2.plot(locals()[dfn]['datetime'], locals()[dfn][xx]*100, label=xx)
# mfmt=mds.DateFormatter('%m-%d-%H')
# ax1.xaxis.set_major_formatter(mfmt)
# ax1.xaxis.set_(interval=1)
#ax2.tick_params(axis='x', which='both', bottom=False)
#ax2.tick_params(labelbottom=False)
#plt.setp(ax2.get_xticklabels(),visible=False)
figi.tight_layout()

解决方案

核心思路是统一使用ax1的X轴刻度控制,同时隐藏ax2的X轴刻度,并通过日期定位器设置合理的刻度间隔:

  1. 导入matplotlib.dates模块,用于日期刻度的精准控制
  2. 给ax1设置日期定位器和格式化器,指定或自动选择合适的刻度间隔
  3. 完全隐藏ax2的X轴刻度和标签,避免其干扰ax1的X轴显示

修改后的完整代码:

import matplotlib.dates as mdates

figi, ax1=plt.subplots()
ax1.plot(locals()[edfn].datetime, locals()[edfn].ic_mean, label='ic mean')
ax2=ax1.twinx()

# 设置ax1的X轴刻度:自动选择合适间隔,也可手动指定比如每1小时一个刻度
ax1.xaxis.set_major_locator(mdates.AutoDateLocator())
# 设置日期显示格式,可根据需求调整
ax1.xaxis.set_major_formatter(mdates.DateFormatter('%m-%d-%H'))

# 隐藏ax2的X轴刻度与标签,避免重复显示
ax2.tick_params(axis='x', which='both', bottom=False, labelbottom=False)
plt.setp(ax2.get_xticklabels(), visible=False)

# 其他绘图设置
ax1.legend(title='gauge name', loc='upper left')
ax1.set_ylabel('Rain (mm)', rotation=90)
ax1.set_xlabel('Datetime')
ax1.tick_params(axis='x', rotation=90)
ax2.plot(locals()[dfn]['datetime'], locals()[dfn][xx]*100, label=xx)

figi.tight_layout()
plt.show()

如果需要强制固定刻度间隔(比如每1小时一个刻度),可以把AutoDateLocator()替换为mdates.HourLocator(interval=1),这样无论数据分辨率多高,X轴都会按指定间隔显示刻度。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 20:57:17