如何使 mplcursors 模块只显示绘制在折线图上的点的标签
how to make the mplcursors module only show labels for points plotted on a line graph
所以我有一个折线图,其中 python 中的 mplcursors 模块显示了它上面任意点的坐标。
我希望它只显示明确标绘的点的标签,而不是标绘点之间恰好在连接它们的线上的标签。
如果你愿意,我愿意用代码更新问题。
一种方法是为相同的点创建一个不可见的散点图,并将 mplcursor
附加到它。
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
x = np.arange(30)
y = 30 + np.random.randint(-5, 6, x.size).cumsum()
fig, ax = plt.subplots()
ax.plot(x, y)
dots = ax.scatter(x, y, color='none')
mplcursors.cursor(dots, hover=True)
plt.show()
该功能可以包装到辅助函数中:
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
def create_mplcursor_for_points_on_line(lines, ax=None, annotation_func=None, **kwargs):
ax = ax or plt.gca()
scats = [ax.scatter(x=line.get_xdata(), y=line.get_ydata(), color='none') for line in lines]
cursor = mplcursors.cursor(scats, **kwargs)
if annotation_func is not None:
cursor.connect('add', annotation_func)
return cursor
x = np.arange(10, 301, 10)
y = 30 + np.random.randint(-5, 6, x.size).cumsum()
fig, ax = plt.subplots()
lines = ax.plot(x, y)
cursor = create_mplcursor_for_points_on_line(lines, ax=ax, hover=True)
plt.show()
I cannot show the whole code
我找到了解决这个问题的好办法。您可以使用 mplcursor 函数提取折线图的数据点。
# Label functions
def show_datapoints(sel):
xi, yi = sel[0], sel[0]
xi, yi = xi._xorig.tolist(), yi._yorig.tolist()
sel.annotation.set_text('x: '+ str(xi[round(sel.target.index)]) +'\n'+ 'y: '+ str(yi[round(sel.target.index)]))
调用 mplcursor 中的 show_datapoints 函数显示数据点
mplcursors.cursor(self.ax1).connect('add',show_datapoints)
所以我有一个折线图,其中 python 中的 mplcursors 模块显示了它上面任意点的坐标。
我希望它只显示明确标绘的点的标签,而不是标绘点之间恰好在连接它们的线上的标签。
如果你愿意,我愿意用代码更新问题。
一种方法是为相同的点创建一个不可见的散点图,并将 mplcursor
附加到它。
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
x = np.arange(30)
y = 30 + np.random.randint(-5, 6, x.size).cumsum()
fig, ax = plt.subplots()
ax.plot(x, y)
dots = ax.scatter(x, y, color='none')
mplcursors.cursor(dots, hover=True)
plt.show()
该功能可以包装到辅助函数中:
import matplotlib.pyplot as plt
import numpy as np
import mplcursors
def create_mplcursor_for_points_on_line(lines, ax=None, annotation_func=None, **kwargs):
ax = ax or plt.gca()
scats = [ax.scatter(x=line.get_xdata(), y=line.get_ydata(), color='none') for line in lines]
cursor = mplcursors.cursor(scats, **kwargs)
if annotation_func is not None:
cursor.connect('add', annotation_func)
return cursor
x = np.arange(10, 301, 10)
y = 30 + np.random.randint(-5, 6, x.size).cumsum()
fig, ax = plt.subplots()
lines = ax.plot(x, y)
cursor = create_mplcursor_for_points_on_line(lines, ax=ax, hover=True)
plt.show()
I cannot show the whole code
我找到了解决这个问题的好办法。您可以使用 mplcursor 函数提取折线图的数据点。
# Label functions
def show_datapoints(sel):
xi, yi = sel[0], sel[0]
xi, yi = xi._xorig.tolist(), yi._yorig.tolist()
sel.annotation.set_text('x: '+ str(xi[round(sel.target.index)]) +'\n'+ 'y: '+ str(yi[round(sel.target.index)]))
调用 mplcursor 中的 show_datapoints 函数显示数据点
mplcursors.cursor(self.ax1).connect('add',show_datapoints)