如何使用matplotlib在单击和悬停时显示散点值? IAM是matplotlib的新手

问题描述

这是我想做的事情:

这是我用于颜色参考的数据
#以浮点格式创建cqi列列表

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()

解决方法

好的,我找到了解决方法。 iam使用以下annote方法。

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)

然后定义一个根据索引i更新注释值的函数,它将从click事件中接收。

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)

完整代码可以找到here