python - 如何使 mplcursors 模块仅显示折线图上绘制的点的标签

标签 python matplotlib plot mplcursors

所以我有一个折线图,其中 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()
example plot
该功能可以包装到一个辅助函数中:
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()

关于python - 如何使 mplcursors 模块仅显示折线图上绘制的点的标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63530556/

相关文章:

python - 大型 Python 随机共享器

python - Matplotlib - 箱线图腿是最小值和最大值

python - 彩色 Pandas 时间序列按列绘制

r - 为什么这不在一张图中绘制多个函数?

python - sklearn、python 中的网格搜索技术

python - 将数据与另一个数据框中两列中的数据进行比较以填充第一个数据框中的第三列

python - 在 matplotlib 子图中放大绘图

python - 在 Seaborn FacetGrid 中绘制多个 DataFrame 列

python - 从单词表中查找字符串和子字符串

python - 阻止 Matplotlib Jupyter notebooks 显示带有动画的情节