mplcursors 仅显示 y 坐标

mplcursors shows only y coordinate

我正在用 pyqt 做一个应用程序,有一个用 matplotlib 构建的绘图。我用mplcursors显示坐标,但它不显示x坐标:


看我的代码canvas:

class Canvas(FigureCanvas):
    def __init__(self, parent=None, width=5, height=5, dpi=120):
        fig = Figure(figsize=(width, height), dpi=dpi)
        self.axes = fig.add_subplot(111)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.plot()


    def plot(self):
            x = ['22-02 11:16:15', '22-02 15:31:54', '22-02 15:32:30',
                 '22-02 15:32:45', '22-02 15:33:57', '22-02 15:34:13',
             '22-02 15:34:46']
            y = [1, 4, 3, 4, 8, 9, 2]
            self.figure.tight_layout()
            self.figure.autofmt_xdate()
            #mplcursors.Cursor()

            ax = self.figure.add_subplot(111)

            dt = ax.plot(x, y)
            cursor = mplcursors.cursor(dt, hover = True)

请注意,示例中没有给出数字时间戳。 Matplotlib 将它们解释为文本标签并将它们编号为 0,1,2,...,N-1。另请注意,时间间隔不均,但 matplotlib 显示在 x 轴上均匀间隔的精确 x 标签。

要显示 x 轴,显式注释函数可以解释数字 x 坐标(在 0 到 N-1 范围内),将其四舍五入并将其用作字符串列表的索引。在这种情况下,x 坐标将显示最近的 x 标签,而 y 值将被很好地插值。

这是一些示例代码:

from matplotlib import pyplot as plt
import mplcursors

def show_annotation(sel):
    xi, yi = sel.target
    xi = int(round(xi))
    sel.annotation.set_text(f'{x[xi]}\nvalue:{yi:.3f}')

x = ['22-02 11:16:15', '22-02 15:31:54', '22-02 15:32:30',
     '22-02 15:32:45', '22-02 15:33:57', '22-02 15:34:13',
     '22-02 15:34:46']
y = [1, 4, 3, 4, 8, 9, 2]

figure, ax = plt.subplots()
dt = ax.plot(x, y)

cursor = mplcursors.cursor(dt, hover=True)
cursor.connect('add', show_annotation)

figure.tight_layout()
figure.autofmt_xdate() # has no effect, because matplotlib only encountered texts for the x-axis

plt.show()

如果您还需要 x 的完全内插时间戳,您应该将 x 转换为数字时间戳。还要注意提供年份,因为默认年份为 1901,这可能会在闰年期间导致冲突。

在下面的示例代码中,第一个时间戳被修改为与其余时间一起。该图现在使用与时间成比例的距离。

from matplotlib import pyplot as plt
from matplotlib import dates as mdates
import mplcursors
from datetime import datetime

def show_annotation(sel):
    xi, yi = sel.target
    sel.annotation.set_text(f"{mdates.DateFormatter('%d %b %H:%M:%S')(xi)}\nvalue:{yi:.3f}")

x = ['22-02 15:31:15', '22-02 15:31:54', '22-02 15:32:30',
     '22-02 15:32:45', '22-02 15:33:57', '22-02 15:34:13',
     '22-02 15:34:46']
# first, convert the strings to datetime objects, and then convert to a numerical time
# as the day is put before the month, a specific format conversion needs to be supplied
# the year needs to be prepended to get the timestamps in the correct year
x = [mdates.date2num(datetime.strptime('2020-'+xi, '%Y-%d-%m %H:%M:%S')) for xi in x]
y = [1, 4, 3, 4, 8, 9, 2]

figure, ax = plt.subplots()
dt = ax.plot(x, y)
ax.xaxis_date()
# display the time on two lines: the day and the shortened month name, and then HH:MM:SS
ax.xaxis.set_major_formatter(mdates.DateFormatter('%d %b\n%H:%M:%S'))
# ax.set_xticks(x) # to set the input time stamps as xticks

figure.tight_layout()

cursor = mplcursors.cursor(dt, hover=True)
cursor.connect('add', show_annotation)

plt.show()