我试图制作它,但在执行时,它显示以下错误:
bar,=plt.bar(xpos,revenue)
ValueError:要解压缩的值太多
我如何解决它,因为我希望在悬停鼠标时注释中的x
和y
值。这是我的以下代码:
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()
答案 0 :(得分:3)
该错误告诉您plt.bar
返回单个对象,该对象无法解压缩。所以你需要删除逗号(,
)。而是将返回的条形容器称为bars = plt.bar(xpos,revenue)
。
你也不能盲目地复制some other solution for scatters or plots吧。相反,你需要调整它到酒吧。所以你需要经过这些酒吧并检查它们中的哪一个(如果有的话)悬停。
请在此处查看完整的解决方案:
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()