Matplotlib中axvspan时间区间着色触发ConversionError的解决咨询
解决Matplotlib axvspan时间转换错误问题
错误原因在于你传给axvspan的是纯时间字符串(如"13:00"),但x轴的TradeTimeUtc是带日期的datetime类型,Matplotlib无法将纯时间字符串转换为匹配的轴单位,因此触发ConversionError。
解决步骤:
- 结合循环中的
date变量,将纯时间字符串转换为完整的datetime对象,确保和x轴数据类型一致。 - 使用
pandas.to_datetime或Python标准库datetime拼接日期与时间。
修改后的代码片段:
for date in dates: data = df[df['TradeTimeUtc'].dt.date == date] fig, ax1 = plt.subplots() # plot spread on primary axis ax1.plot(data['TradeTimeUtc'], data['spread'], color='blue') ax1.set_xlabel('TradeTimeUtc') ax1.set_ylabel('spread', color='blue') ax1.tick_params('y', colors='blue') # 修正:将时间字符串转换为带日期的datetime对象 start_time = pd.to_datetime(f"{date} 13:00") end_time = pd.to_datetime(f"{date} 14:00") ax1.axvspan(start_time, end_time, alpha=0.2, color='gray') # create a secondary axis for Volume ax2 = ax1.twinx() # plot Volume on secondary axis as a bar chart ax2.bar(data['TradeTimeUtc'], data['acc_vol'], width = 0.0003, color='red', alpha=0.1) ax2.set_ylabel('Volume', color='red') ax2.tick_params('y', colors='red') # set plot title ax1.set_title(f'Spread and Volume on {date}') # adjust layout fig.tight_layout() # show plot plt.show()
额外说明:
如果你的date变量是Python原生datetime.date对象,也可以用标准库拼接:
from datetime import datetime, time start_time = datetime.combine(date, time(13, 0)) end_time = datetime.combine(date, time(14, 0))
这样axvspan就能正确识别时间范围,匹配x轴的datetime类型数据,不会再触发转换错误。
内容的提问来源于stack exchange,提问作者kit12_31
相关产品推荐
相关产品推荐

