如何绘制无隔夜及周末间隙的1分钟价格数据折线图
解决Matplotlib绘制交易时段数据时的间隙问题
你遇到的问题根源是过滤后的datetime索引本身存在非连续的时间间隔(比如每日18点到次日7点、周末),Matplotlib会按照实际时间差绘制,因此出现跨间隙的难看直线。要实现数据点连续连接且保留原时间戳的效果,只需用连续的整数位置绘图,再将原datetime标签映射回X轴即可。
修改后的代码示例
import matplotlib.pyplot as plt import matplotlib.dates as mdates # 你的原始数据过滤逻辑 s = a series of data mask = (s.index.dayofweek < 5) & (s.index.hour >= 7) & (s.index.hour < 18) filtered_prices = s[mask] fig, ax = plt.subplots(figsize=(12, 6)) # 用连续整数位置作为x轴,确保数据点连续连接 x = range(len(filtered_prices)) ax.plot(x, filtered_prices.values) # 方案1:手动设置刻度间隔(适合小数据量) # 每120个点取一个标签(对应2小时,1分钟一个数据点) n = 120 ax.set_xticks(x[::n]) ax.set_xticklabels(filtered_prices.index[::n].strftime('%Y-%m-%d %H:%M'), rotation=45) # 方案2:自动日期刻度(适合大数据量,更智能) # ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M')) # ax.xaxis.set_major_locator(mdates.HourLocator(interval=2)) # 每2小时生成一个刻度 # 轴标签与标题设置 ax.set_xlabel('Date') ax.set_ylabel('Price') ax.set_title('Price Data for April 2023 (Weekdays 7am-6pm)') plt.tight_layout() # 自动调整布局,避免标签被截断 plt.show()
关键逻辑说明
- 连续x轴位置:用
range(len(filtered_prices))生成连续整数序列作为绘图的x轴,让每个数据点之间的间隔统一为1,彻底消除时间间隙导致的直线。 - 时间戳映射:将过滤后的datetime索引按间隔提取,作为X轴的刻度标签,既保留原时间信息,又避免标签重叠。
- 布局优化:
tight_layout()自动调整图表元素位置,防止日期标签被截断。
内容的提问来源于stack exchange,提问作者user21594319
相关产品推荐
相关产品推荐

