【问题标题】:Matplotlib Scatter plot interactivity not workingMatplotlib 散点图交互性不起作用
【发布时间】:2023-03-18 18:40:01
【问题描述】:

直到今天早上,当我将点悬停在散点图上时,我才能够显示标签信息。 现在,如果我运行以下代码,它不会显示任何错误,但交互性不起作用,并且看起来 mplconnect 或 mlpcursors 完全被忽略了。 我在 windows 和 Fedora 下尝试过相同的代码。 不明白发生了什么。

从 matplotlib.pyplot 导入图,显示 将 numpy 导入为 npy 从 numpy.random 导入 rand

    x, y, c, s = rand(4, 100)
    def onpick3(event):
        ind = event.ind
        print('onpick3 scatter:', ind, npy.take(x, ind), npy.take(y, ind))

    fig = figure()
    ax1 = fig.add_subplot(111)
    col = ax1.scatter(x, y, 100*s, c, picker=True)
    #fig.savefig('pscoll.eps')
    fig.canvas.mpl_connect('pick_event', onpick3)

show()

或者

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(1)

x = np.random.rand(15)
y = np.random.rand(15)
names = np.array(list("ABCDEFGHIJKLMNO"))
c = np.random.randint(1,5,size=15)

norm = plt.Normalize(1,4)
cmap = plt.cm.RdYlGn

fig,ax = plt.subplots()
sc = plt.scatter(x,y,c=c, s=100, cmap=cmap, norm=norm)

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 = sc.get_offsets()[ind["ind"][0]]
    annot.xy = pos
    text = "{}, {}".format(" ".join(list(map(str,ind["ind"]))), 
                           " ".join([names[n] for n in ind["ind"]]))
    annot.set_text(text)
    annot.get_bbox_patch().set_facecolor(cmap(norm(c[ind["ind"][0]])))
    annot.get_bbox_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = sc.contains(event)
        if cont:
            update_annot(ind)
            annot.set_visible(True)
            fig.canvas.draw_idle()
        else:
            if vis:
                annot.set_visible(False)
                fig.canvas.draw_idle()

fig.canvas.mpl_connect("motion_notify_event", hover)

plt.show()

这不是我的代码,我是从网站上复制粘贴的,但行为是一样的。

【问题讨论】:

    标签: python-3.x scatter-plot interaction mousehover


    【解决方案1】:

    Plotly express 解决问题

    将 plotly.express 导入为 px

    alpha = data[data['Ticker']==focus].V1
    gamma = data[data['Ticker']==focus].V2
    
    fig = px.scatter(data, x='V1', y='V2', color=Colors.Market_Cap, hover_data=["Ticker"] )
    fig.add_shape(type="circle",
        xref="x", yref="y",
        x0=int(alpha-3), y0=int(gamma-3), x1=int(alpha+3), y1=int(gamma+3),
        line_color="LightSeaGreen",
    )
    
    fig.show()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-01
      • 2021-03-07
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 2020-07-22
      相关资源
      最近更新 更多