仅将鼠标悬停在实际数据点上

时间:2019-08-15 16:33:17

标签: matplotlib jupyter-notebook

这是一个非常简单的折线图。

%matplotlib notebook
import matplotlib.pyplot as plt

lines = plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.setp(lines,marker='D')
plt.ylabel('foo')
plt.xlabel('bar')
plt.show()

如果将鼠标移到图表上,无论指针在哪里,我都会得到x和y值。有什么方法只能在我实际上在数据点上时才获取值?

1 个答案:

答案 0 :(得分:0)

我知道您想修改绘图右下方状态栏中显示的坐标的行为,对吗?

如果是这样,您可以“劫持” Axes.format_coord()函数以使其显示所需的内容。您可以在matplotlib的示例库中看到an example of this

在您的情况下,类似的东西似乎可以解决问题?

my_x = np.array([1, 2, 3, 4])
my_y = np.array([1, 4, 9, 16])
eps = 0.1

def format_coord(x, y):
    close_x = np.isclose(my_x, x, atol=eps)
    close_y = np.isclose(my_y, y, atol=eps)
    if np.any(close_x) and np.any(close_y):
        return 'x=%s y=%s' % (ax.format_xdata(my_x[close_x]), ax.format_ydata(my_y[close_y]))
    else:
        return ''

fig, ax = plt.subplots()
ax.plot(my_x, my_y, 'D-')
ax.set_ylabel('foo')
ax.set_xlabel('bar')
ax.format_coord = format_coord

plt.show()