饼图中的matplotlib mouseclick事件 [英] matplotlib mouseclick event in pie chart

查看:481
本文介绍了饼图中的matplotlib mouseclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在matplotlib和Python中是否有一种方法可以返回在饼图中单击的值/标签.例如,如果用户单击饼形图的条形图A,则返回值A.如果用户单击B饼形图的条形图B,则返回值B.

解决方案

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

参考:

为matplotlib的imshow中的颜色值?

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

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.

解决方案

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

这篇关于饼图中的matplotlib mouseclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆