mplfinance plot正确,但日期时间格式奇怪



我用mplfinance绘制股票数据,它工作得很好。但是我很难从x轴上得到正确的日期。当我使用这段代码时,函数on_mouse_click显示了1970-02-02和65.6这样的结果。65.6显然是正确的,但我绘制的是2022年和2023年的数据。我用DateFormatters等尝试了几种方法,但我认为这是set_xlim的问题。或者别的什么。什么好主意吗?下面是我的代码:

class MyMplCanvas(FigureCanvas):
def __init__(self, parent=None, width=5, height=4, dpi=300):        
self.fig, ax = plt.subplots(2, 1, sharex=True, 
gridspec_kw={'height_ratios': [4, 1]})
plt.subplots_adjust(hspace = 0)
plt.rcParams['axes.grid'] = True
self.ax = ax[0]
self.volax = ax[1]


super().__init__(self.fig)
self.setParent(parent)
self.mpl_connect('button_press_event', self.on_mouse_click)


def on_mouse_click(self, event):
if event.button == 3: # Right mouse button
x, y = event.xdata, event.ydata
date_str = mdates.num2date(x).strftime('%Y-%m-%d')
msg = f'Datum: {date_str}nPrice: {y:.2f}'
QMessageBox.information(self, 'Mouse Position', msg)

如果您使用mplfinance来绘制数据,而没有设置show_nontrading=True,那么您的右击日期显示转换是不正确的。

你有两个选择,其中任何一个都可以解决这个问题,但不能同时解决:

  1. 调用mplfinance时设置show_nontrading=True
  2. 修改你的转换如下…注意xxdate的转换以及在xdate上直接调用.strftime()。我假设self.df是您传递到mplfinance的数据框架,但如果不是,那么找到该数据框架并使用该数据框架。DatetimeIndex将x转换为xdate
def on_mouse_click(self, event):
if event.button == 3: # Right mouse button
x, y = event.xdata, event.ydata
# --- modified code here:
xdate = self.df.index[int(x)]
date_str = xdate.strftime('%Y-%m-%d')
# --- until here ---
msg = f'Datum: {date_str}nPrice: {y:.2f}'
QMessageBox.information(self, 'Mouse Position', msg)

有关更多信息,请阅读Mplfinance时间轴关注点…

最新更新