0

Is there a way in matplotlib and Python to return the value/label clicked in a pie chart. For example if user clicks on sliver A of pie chart, return value A. If user clicks on sliver B of B pie chart, return value B.

user1314011
  • 153
  • 2
  • 5
  • 12
  • You can do this with callbacks. See http://stackoverflow.com/questions/5836560/color-values-in-imshow-for-matplotlib?lq=1 . You need to do something similar to capture the mouse location and then figure out which slice the click is in. – tacaswell Sep 26 '12 at 18:28
  • The solution linked here is for a image plot, and it can get back the color based on the coordinate computed. But it seems not possible with pie chart? – user1314011 Sep 27 '12 at 02:08

2 Answers2

4
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])

references:

Color values in imshow for matplotlib?

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

Community
  • 1
  • 1
tacaswell
  • 84,579
  • 22
  • 210
  • 199
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()
Jry9972
  • 463
  • 7
  • 16