我正在制作一个程序来快速分析电池充电器等的测试曲线。我想结合悬停框,它用一条垂直线捕捉到每条曲线,以便于比较。如果我激活这两个代码,它们会发生碰撞,并且在移动鼠标时会出现一条线,当我停止它时它会消失并且悬停框不会与曲线对齐。
悬停框是由 mplcursors 库制作的,而线条是由 matplotlib 中的光标小部件制作的。
cursor = Cursor(
ax2, useblit=True, horizOn=False, vertOn=True, color="red", linewidth=0.5
)
mplcursors.cursor(hover=True)
完整代码在这里:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor
import mplcursors
data = np.loadtxt("test.txt")
x = data[:, 0]
y = data[:, 1]
y2 = data[:, 2]
y3 = data[:, 3]
fig = plt.figure(figsize=(13, 5))
ax = fig.add_subplot(111)
ax.plot(x, y, "--", label="Voltage")
ax.plot(x, y2, "-.", label="Current")
ax2 = ax.twinx()
ax2.plot(x, y3, "g:", label="Temperature")
ax2.set_ylabel("Celsius", color=("LightBlue"))
ax2.set_ylim(18, 100)
fig.legend(
edgecolor=("DarkBlue"),
facecolor=("LightBlue"),
loc="upper right",
bbox_to_anchor=(1, 1),
bbox_transform=ax.transAxes,
)
ax.set_title("Test Surveillance", color=("Purple"))
ax.set_xlabel("Milliseconds", color=("LightGreen"))
ax.set_ylabel("Volts and Amps", color=("DarkGrey"))
plt.xlim(0)
# cursor = Cursor(
# ax2, useblit=True, horizOn=False, vertOn=True, color="red", linewidth=0.5
# )
mplcursors.cursor(hover=True)
plt.show()
作为一个额外的好处:X 值在示例中以秒为单位(我知道它表示毫秒)。我想显示 1:45:24 或图片中 x=5.77e+04 的任何内容。这可能吗?