2016-04-06 32 views
0

这是一个pyplot.barh示例。当用户点击红色或绿色条时,脚本应该获得条形图的值,所以我在图4中添加了pick_event。 enter image description herematplotlib pick_event不适用于barh?

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

但没有happend当我点击颜色栏。为什么它没有反应?

回答

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列表。

我会让你根据自己的喜好重新设置情节。

+0

Greate!所以,当绘图时,魔法增加了一个argv'picker = True'。但在我的情况下,它并不完美。因为使用双轴(axb = axt.twiny()),只有一个边有反应(绿色边)。可能是双轴工作。 – dindom

相关问题