Matplotlib绘制K线图时X轴仅显示日期 未按15分钟时间间隔排布
问题根因
不是程序未读取完整Datetime时间,核心错误是K线宽度的单位设置不匹配时间粒度:
- 当X轴传入pandas Timestamp类型的时间索引时,
plt.bar()的width参数默认单位是天 - 你当前设置的
width = .5代表0.5天(即12小时)宽度,而你的数据是15分钟粒度,相邻两根K线的时间间隔仅为15/(24*60) ≈ 0.0104天,0.5天的宽度比相邻K线间隔大48倍,所有K线自然会完全堆叠在一起,视觉上看起来像是挤在X轴同一位置。
修复方法
- 把K线宽度调整为和15分钟粒度匹配的数值,按天为单位计算:实体宽度设为15分钟间隔的80%左右避免粘连,上下影线宽度设为间隔的10%即可
- 额外添加X轴时间格式化配置,避免X轴默认只显示日期、不显示时分秒的问题
修正后代码
import matplotlib.dates as mdates ## PLOT Candles plt.figure(figsize=(12,6)) # 按15分钟粒度定义K线元素宽度,单位:天 width = 15/(24*60)*0.8 # K线实体宽度占15分钟间隔的80%,留空隙避免粘连 width2 = 15/(24*60)*0.1 # 上下影线宽度占间隔的10% #define up and down prices up = df[df.close>=df.open] down = df[df.close<df.open] #define colors to use col1 = 'green' col2 = 'red' col3 = 'blue' col4 = 'grey' #plot up prices plt.bar(up.index,up.close-up.open,width,bottom=up.open,color=col1) plt.bar(up.index,up.high-up.close,width2,bottom=up.close,color=col1) plt.bar(up.index,up.low-up.open,width2,bottom=up.open,color=col1) #plot down prices plt.bar(down.index,down.close-down.open,width,bottom=down.open,color=col2) plt.bar(down.index,down.high-down.open,width2,bottom=down.open,color=col2) plt.bar(down.index,down.low-down.close,width2,bottom=down.close,color=col2) # 格式化X轴时间标签,显示日期+时分秒,自动旋转避免重叠 plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M')) plt.gcf().autofmt_xdate() plt.show()
内容的提问来源于stack exchange,提问作者veritaS
相关产品推荐
相关产品推荐

