【问题标题】:How to use Radio Buttons to control a pie chart matplotlib?如何使用单选按钮来控制饼图 matplotlib?
【发布时间】:2022-01-27 08:21:16
【问题描述】:

我的代码有一个小问题,希望有人能帮助我。因此,我创建了一个饼图,并使用 RadioButtons 来“控制”“爆炸参数”。预期结果:我们有一个饼图,我们有 Radiobutton,当我们单击一个单选按钮时,在饼图中与单击的 Radiobutton 匹配的“serie”被拉出(感谢“explode”),我们可以做到这一点只要我们愿意。

我的问题:我创建了单选按钮,当它们被点击时,它会打开一个新窗口,显示预期的结果,但我希望饼图和单选按钮在同一个窗口中。

我的代码就在下面:

import matplotlib.pyplot as plt
from matplotlib.widgets import RadioButtons
rax = plt.axes([0.05, 0.7, 0.15, 0.15])
radio = RadioButtons(rax, ('0-4 ans', '5-10 ans', '11-13 ans', '14-17 ans'))
def explode_function(label):
    labels = '0-4 ans', '5-10 ans', '11-13 ans', '14-17 ans'
    sizes = [17.4, 25.7, 18.6, 38.3]
    explode = (0, 0, 0, 0)  # only "explode" the 2nd slice (i.e. 'Hogs')
    fig1, ax = plt.subplots()
    if label == '0-4 ans':
        explode = (0.15, 0, 0, 0)
    elif label == '5-10 ans':
        explode = (0, 0.15, 0, 0)
    elif label == '11-13 ans':
        explode = (0, 0, 0.15, 0)
    elif label == '14-17 ans':
        explode = (0, 0, 0, 0.15)
    ax.pie (sizes, explode=explode, labels=labels, autopct='%1.1f%%',
        shadow=True, colors=['lightblue', 'lightgreen', 'salmon', 'lightgray'])
    plt.show()
radio.on_clicked(explode_function)
plt.show()```

Thanks a lot, and good evening 

【问题讨论】:

    标签: matplotlib button charts radio


    【解决方案1】:

    通过在explode_function 中创建figax,每次单击单选按钮时都会生成一个新图。预先创建figax,允许不断地使用相同的情节。作为初始化,explode_function(labels[0]) 已经显示了饼图的一种变体。 fig.canvas.redraw() 强制绘制更新的图表。

    import matplotlib.pyplot as plt
    from matplotlib.widgets import RadioButtons
    
    fig = plt.figure()
    ax = plt.subplot(1, 1, 1)
    rax = plt.axes([0.05, 0.7, 0.15, 0.15])
    labels = '0-4 ans', '5-10 ans', '11-13 ans', '14-17 ans'
    radio = RadioButtons(rax, labels)
    
    def explode_function(label):
        ax.cla()
        sizes = [17.4, 25.7, 18.6, 38.3]
        explode = [0.15 if label == label_i else 0 for label_i in labels]
        ax.pie(sizes, explode=explode, labels=labels, autopct='%1.1f%%',
               shadow=True, colors=['lightblue', 'lightgreen', 'salmon', 'lightgray'])
        fig.canvas.draw()
    
    explode_function(labels[0])
    radio.on_clicked(explode_function)
    plt.show()
    

    【讨论】:

    • 哦!谢谢它有效,这正是我所需要的,非常感谢!
    猜你喜欢
    • 2017-06-11
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-15
    • 2015-08-07
    相关资源
    最近更新 更多