首页 > 解决方案 > 如何使用 matplotlib 在单击和悬停时显示散点值?我是 matplotlib 的新手

问题描述

这是我想要做的:

这是我用于颜色参考的数据
#create list of cqi column in float format

li=[]

for x in data.lte_cqi_cw0_1:
    li.append(float(x))

我从导入的 csv 为 x 和 y 轴数据创建了一个列表

#create x and y axis data
x = []
y = []
for a in data.positioning_lon:
    x.append(float(a))
for a in data.positioning_lat:
    y.append(float(a))
 

设置颜色条件

c = np.where(data.lte_cqi_cw0_1 < 7, 'r', 'g')

#plot the map
fig, ax=plt.subplots()
scatter=ax.scatter(x,y,c=c)

我正在使用这种方法来显示每个点的值。我想使用 on_click 事件和悬停事件来显示基于鼠标移动的值。

#display each point value        
for i, value in enumerate(li):
    
    annot = ax.annotate(value,(x[i], y[i]))
    annot.set_visible(False)


#set legend
red = mpatches.Patch(color='red', label="0 to 7 - " + str(low_per) + "%")
green = mpatches.Patch(color='green', label="7 to 15 - " + str(high_per) + "%")
plt.legend(handles=[red , green ])

plt.show()

标签: pythonmatplotlibonclickhoverscatter

解决方案


好的,我找到了解决方案。我使用以下注释方法。

annot = ax.annotate("", xy=(0,0), xytext=(20,20),textcoords="offset points",
                    bbox=dict(boxstyle="round", fc="w"),arrowprops=dict(arrowstyle="- 
>"))
annot.set_visible(False)

然后定义一个函数来根据索引更新注释值,我将从点击事件中收到。

def update_annot(ind):
    pos = scatter.get_offsets()[ind]
    annot.xy = pos
    text = " CQI {}".format(" ".join([str(round(li[ind],2))]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor((c[ind]))
    annot.get_bbox_patch().set_alpha(0.4)
    return text

以下 onpick 功能对我的目标来说工作正常。

def onpick(event):
    #vis = annot.get_visible()
    #annot.set_visible(True)
    global ind
    ind = event.ind[-1]
    print("first value ind"+str(ind))

    update_annot(ind)
    annot.set_visible(True)
    fig.canvas.draw_idle()
    #print (len(ind))
    #print('onpick points:', update_annot(ind))

我也弄清楚了按键事件,如下所示。

def press(event):
    key = event.key
    sys.stdout.flush()
    global ind
    if key == 'left':

        ind += 1
        print("2nd value ind" + str(ind))
        update_annot(ind)
        annot.set_visible(True)
        fig.canvas.draw_idle()
    elif key == 'right':

        ind -= 1
        print("3rd value ind" + str(ind))
        update_annot(ind)
        annot.set_visible(True)
        fig.canvas.draw_idle()

然后将 onpick 和 keypress 函数连接到 matplotlib 的内部函数。

fig.canvas.mpl_connect('pick_event', onpick)
fig.canvas.mpl_connect('key_press_event', press)

完整的代码可以在这里找到


推荐阅读