将鼠标悬停在条形图上时如何注释X和Y的值 [英] How to annotate the values of X and Y while hovering mouse over the bar graph

查看:73
本文介绍了将鼠标悬停在条形图上时如何注释X和Y的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做到这一点,但是在执行时,它显示了以下错误:

I have tried to make it but while executing, it shows me the following error:

bar,=plt.bar(xpos,revenue)

ValueError:太多值无法解包

ValueError: too many values to unpack

我如何解决它,因为我希望在悬停鼠标时在注释中添加xy的值.这是我的以下代码:

how can i solve it as i want values of x and y in the annotate while hover mouse. This is my following code:

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

bar,=plt.bar(xpos,revenue)


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

def update_annot(ind):
    x,y = bar.get_data()
    x0 = x[ind["ind"][0]]
    y0 = y[ind["ind"][0]]
    annot.xy = (x0, y0)
    text = "({:.2g},{:.2g})".format(
        x0,y0,
    )
    annot.set_text(text)
    annot.get_bbox_patch().set_alpha(0.4)

def hover(event):
    vis = annot.get_visible()
    if event.inaxes == ax:
        cont, ind = bar.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()

推荐答案

该错误告诉您plt.bar返回一个无法解压缩的对象.因此,您需要删除逗号(,).而是使用诸如bars = plt.bar(xpos,revenue)之类的名称来调用返回的bar容器.

The error tells you that plt.bar returns a single object, which cannot be unpacked. So you need to remove the comma (,). Instead call the returned bar container something like bars = plt.bar(xpos,revenue).

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

You also cannot blindly copy some other solution for scatters or plots for bars. Instead you need to adapt it to the bars. So you need to go through the bars and check which of them, if any, is hovered.

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

See a complete solution here:

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",
                    bbox=dict(boxstyle="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_bbox_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()

这篇关于将鼠标悬停在条形图上时如何注释X和Y的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆