您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

将鼠标悬停在条形图上时如何注释X和Y的值

将鼠标悬停在条形图上时如何注释X和Y的值

错误告诉您plt.bar返回的单个对象无法解包。因此,您需要删除逗号(,)。而是将返回的bar容器称为bars = plt.bar(xpos,revenue)

您也不能盲目地复制散点图或条形图的其他解决方案。相反,您需要使其适应条形。因此,您需要浏览一下酒吧,并检查其中的哪一个(如果有的话)徘徊。

在此处查看完整的解决方案:

import numpy as np
import matplotlib.pyplot as plt

company=['google','amazon','msft','fb']
revenue=[80,68,54,27]

fig=plt.figure()
ax=plt.subplot()

xpos=np.arange(len(company))

bars = plt.bar(xpos,revenue)


annot = ax.annotate("", xy=(0,0), xytext=(-20,20),textcoords="offset points",
                    b@R_399_2419@=dict(@R_399_2419@style="round", fc="black", ec="b", lw=2),
                    arrowprops=dict(arrowstyle="->"))
annot.set_visible(False)

def update_annot(bar):
    x = bar.get_x()+bar.get_width()/2.
    y = bar.get_y()+bar.get_height()
    annot.xy = (x,y)
    text = "({:.2g},{:.2g})".format( x,y )
    annot.set_text(text)
    annot.get_b@R_399_2419@_patch().set_alpha(0.4)


def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        for bar in bars:
            cont, ind = bar.contains(event)
            if cont:
                update_annot(bar)
                annot.set_visible(True)
                fig.canvas.draw_idle()
                return
    if vis:
        annot.set_visible(False)
        fig.canvas.draw_idle()

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

plt.show()
其他 2022/1/1 18:43:24 有565人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶