首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使mplcursors模块只显示线条图上绘制的点的标签

如何使mplcursors模块只显示线条图上绘制的点的标签
EN

Stack Overflow用户
提问于 2020-08-21 22:01:15
回答 2查看 745关注 0票数 4

因此,我有一个线条图,其中python中的mplcursors模块显示了它上任意点的坐标。

我希望它只显示那些被显式绘制的点的标签,而不是那些在所绘制的点之间并且恰好在连接它们的线路上的标记。

如果你愿意的话,我愿意用代码更新这个问题。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-08-21 23:29:43

一种方法是为相同的点创建一个不可见的散点图,并将mplcursor附加到它。

代码语言:javascript
复制
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()

该功能可以封装到一个助手函数中:

代码语言:javascript
复制
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()
票数 6
EN

Stack Overflow用户

发布于 2021-07-30 11:55:02

我不能显示整个代码

我已经找到了解决这个问题的好办法。您可以使用mpl游标函数提取线图的数据点。

代码语言:javascript
复制
# 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函数来显示数据点

代码语言:javascript
复制
mplcursors.cursor(self.ax1).connect('add',show_datapoints)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63530556

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档