同一图表中K线图与散点图X轴偏移问题求助
解决K线图与散点图X轴偏移问题
问题原因
mplfinance绘制K线图时,会自动将X轴转换为基于0的数组索引(而非真实日期数值),而你手动用mdates.date2num()生成的是实际日期的数值坐标,两者坐标系不匹配,导致偏移。
修复方案
直接利用峰值/谷值的数组索引作为X坐标(和mplfinance的K线X轴逻辑对齐),具体代码修改如下:
修改后的完整代码
def add_candlestick_plot(self, tab): # 生成50天的OHLC样本数据 dates = pd.date_range(end=datetime.now(), periods=50, freq='D') data = { 'Open': np.random.uniform(100, 200, len(dates)), 'High': np.random.uniform(110, 210, len(dates)), 'Low': np.random.uniform(90, 190, len(dates)), 'Close': np.random.uniform(95, 205, len(dates)), 'Volume': np.random.randint(1000, 5000, len(dates)) } df = pd.DataFrame(data, index=dates) # 确保K线逻辑合法:High >= Open/Close,Low <= Open/Close df['High'] = df[['Open', 'Close']].max(axis=1) + np.random.uniform(0, 5, len(dates)) df['Low'] = df[['Open', 'Close']].min(axis=1) - np.random.uniform(0, 5, len(dates)) # 检测峰值和谷值 close_prices = df['Close'].values peaks, _ = find_peaks(close_prices, distance=10) troughs, _ = find_peaks(-close_prices, distance=10) # 创建Matplotlib画布和轴 fig, ax = plt.subplots(figsize=(10, 6)) # 绘制K线图 mpf.plot(df, type='candle', ax=ax, volume=False, style='yahoo') # 关键:直接用数组索引作为X坐标,和K线X轴对齐 ax.scatter(peaks, df['Close'].iloc[peaks], color='red', label='峰值', zorder=5) ax.scatter(troughs, df['Close'].iloc[troughs], color='green', label='谷值', zorder=5) ax.legend() # 格式化X轴日期标签,避免自动错位 ax.set_xticks(range(0, len(df), 5)) ax.set_xticklabels(df.index.strftime('%Y-%m-%d')[::5], rotation=45) # 嵌入PyQt5界面 canvas = FigureCanvas(fig) layout = QVBoxLayout(tab) layout.addWidget(canvas)
核心修改点
- 移除
mdates.date2num()转换逻辑,直接使用peaks/troughs本身的数组索引作为散点X坐标 - 手动设置X轴刻度和标签,避免自动格式化导致的日期错位
- 保持
zorder=5确保散点显示在K线图上方
内容的提问来源于stack exchange,提问作者Joe
相关产品推荐
相关产品推荐

