matplotlib pick_事件不适用于barh?

2024-09-28 22:16:54 发布

您现在位置:Python中文网/ 问答频道 /正文

这是一个pyplot.barh公司例子。当用户单击红色或绿色条时,脚本应该获得bar的x&y值,因此我在图中添加pick_事件。 enter image description here

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

# Random data
bottom10 = pd.DataFrame({'amount':-np.sort(np.random.rand(10))})
top10 = pd.DataFrame({'amount':np.sort(np.random.rand(10))[::-1]})

# Create figure and axes for top10
fig,axt = plt.subplots(1)

# Plot top10 on axt
top10.plot.barh(color='red',edgecolor='k',align='edge',ax=axt,legend=False)

# Create twin axes
axb = axt.twiny()

# Plot bottom10 on axb
bottom10.plot.barh(color='green',edgecolor='k',align='edge',ax=axb,legend=False)

# Set some sensible axes limits
axt.set_xlim(0,1.5)
axb.set_xlim(-1.5,0)

# Add some axes labels
axt.set_ylabel('Best items')
axb.set_ylabel('Worst items')

# Need to manually move axb label to right hand side
axb.yaxis.set_label_position('right')
#add event handle 
def onpick(event):
    thisline = event.artist
    xdata = thisline.get_xdata()
    ydata = thisline.get_ydata()
    ind = event.ind
    print 'onpick points:', zip(xdata[ind], ydata[ind])

fig.canvas.mpl_connect('pick_event', onpick)

plt.show()

但是当我点击颜色栏时什么也没有发生。为什么没有反应?在


Tags: importeventasnppltpdsetind
1条回答
网友
1楼 · 发布于 2024-09-28 22:16:54

原因是您必须定义可以识别的artists,并通过mouseclick定义{};然后必须使这些对象pickable。在

这里有一个最小的例子两个hbar图,允许您选择带有mouseclick的对象;我删除了所有格式,以便集中精力解决您所问的问题。在

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from matplotlib.patches import Rectangle

top10 = pd.DataFrame({'amount' : - np.sort(np.random.rand(10))})
bottom10 = pd.DataFrame({'amount' : np.sort(np.random.rand(10))[::-1]})

# Create figure and axes for top10
fig = plt.figure()
axt = fig.add_subplot(1,1,1)
axb = fig.add_subplot(1,1,1)

# Plot top10 on axt
bar_red = top10.plot.barh(color='red', edgecolor='k', align='edge', ax=axt, legend=False, picker=True)
# Plot bottom10 on axb
bar_green = bottom10.plot.barh(color='green', edgecolor='k', align='edge', ax=axb, legend=False, picker=True)

#add event handler 
def onpick(event):
    if isinstance(event.artist, Rectangle):
        print("got the artist", event.artist)

fig.canvas.mpl_connect('pick_event', onpick)
plt.show()

点击几下后,输出可能如下所示:

^{pr2}$

由于您没有指定要对拾取的对象执行什么操作,所以我只打印了它的标准__str__;如果您查找matplotlib文档,您将找到一个可以访问和操作以提取数据的properties列表。在

我让你根据你的喜好重新编排这个情节。在

相关问题 更多 >