【问题标题】:matplotlib mouseclick event in pie chart饼图中的matplotlib mouseclick事件
【发布时间】:2012-09-18 05:14:12
【问题描述】:

matplotlib 和 Python 中有没有办法返回在饼图中单击的值/标签。例如,如果用户点击饼图的条子A,返回值A。如果用户点击B饼图的条子B,返回值B。

【问题讨论】:

  • 你可以通过回调来做到这一点。见stackoverflow.com/questions/5836560/…。您需要执行类似的操作来捕获鼠标位置,然后确定点击在哪个切片中。
  • 这里链接的解决方案是用于图像绘图,它可以根据计算出的坐标取回颜色。但是饼图好像不行?

标签: python matplotlib wxpython matplotlib-basemap


【解决方案1】:
from matplotlib import pyplot as plt
# make a square figure and axes
plt.figure(figsize=(6,6))
ax = plt.axes([0.1, 0.1, 0.8, 0.8])

labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
fracs = [15,30,45, 10]

explode=(0, 0.05, 0, 0)
p = plt.pie(fracs, explode=explode, labels=labels, autopct='%1.1f%%', shadow=True)
plt.title('Raining Hogs and Dogs', bbox={'facecolor':'0.8', 'pad':5})

w = p[0][0]
plt.show() 

class PieEventHandler:
    def __init__(self,p):
        self.p = p
        self.fig = p[0].figure
        self.ax = p[0].axes
        self.fig.canvas.mpl_connect('button_press_event', self.onpress)

    def onpress(self, event):
        if event.inaxes!=self.ax:
            return

        for w in self.p:
            (hit,_) = w.contains(event)
            if hit:
                print w.get_label()


handler = PieEventHandler(p[0])

参考:

Color values in imshow for matplotlib?

http://matplotlib.org/examples/pylab_examples/pie_demo.html

【讨论】:

    【解决方案2】:

    :)

    import matplotlib.pyplot as plt
    
    def main():
        # Make an example pie plot
        fig = plt.figure()
        ax = fig.add_subplot(111)
    
        labels = ['Apple', 'Mango', 'Orange']
        wedges, plt_labels = ax.pie([20, 40, 60], labels=labels)
        ax.axis('equal')
    
        make_picker(fig, wedges)
        plt.show()
    
    def make_picker(fig, wedges):
    
        def onclick(event):
            wedge = event.artist
            label = wedge.get_label()
            print label
    
    # Make wedges selectable
        for wedge in wedges:
            wedge.set_picker(True)
    
        fig.canvas.mpl_connect('pick_event', onclick)
    
    if __name__ == '__main__':
        main()
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-29
      • 2010-12-31
      • 1970-01-01
      相关资源
      最近更新 更多