matplotlib pick_event对于barh不起作用?

时间:2016-04-06 07:55:53

标签: python matplotlib

这是一个pyplot.barh示例。当用户点击红色或绿色条时,脚本应该获得x& y的值为bar,所以我在图中添加了pick_event。 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()

但是当我点击颜色条时没有任何事情发生。为什么没有反应?

1 个答案:

答案 0 :(得分:1)

原因是您必须定义artists可以识别,pickedmouseclick定义;那么你必须创建这些对象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()

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

got the artist Rectangle(-0.951754,9;0.951754x0.5)
got the artist Rectangle(-0.951754,9;0.951754x0.5)
got the artist Rectangle(-0.951754,9;0.951754x0.5)
got the artist Rectangle(0,5;0.531178x0.5)
got the artist Rectangle(0,5;0.531178x0.5)
got the artist Rectangle(0,5;0.531178x0.5)
got the artist Rectangle(0,2;0.733535x0.5)
got the artist Rectangle(0,2;0.733535x0.5)
got the artist Rectangle(0,2;0.733535x0.5)
got the artist Rectangle(-0.423519,2;0.423519x0.5)
got the artist Rectangle(-0.423519,2;0.423519x0.5)

由于您未指定要对拾取的对象执行的操作,因此我仅打印其标准__str__;如果您查找matplotlib文档,您将找到可以访问和操作以提取数据的properties列表。

我会留给您根据您的喜好重新格式化情节。