如何通过单击matplotlib按钮更新条形图?

时间:2018-07-03 02:49:10

标签: matplotlib

问题是如何在单击matplotlib按钮时在原始图形上绘制新图形,而不是像在def getfemale()中注释的那样创建新图形。我的代码仅会绘制在按钮本身上。 请帮我解决这个问题。非常感谢。

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
import pandas as pd

def autolabel(rects):
    for rect in rects:
        height = rect.get_height()
        plt.text(rect.get_x() + rect.get_width() / 2.0 - 0.2, 1.01 * height, '%s' % float(height))
#widget class def()
class Index(object):
    def getmale(self,event):
        x = np.linspace(0,1,30)
        y = 2*x+1
        #plt.figure()
        plt.plot(x,y)
        plt.draw() #plt.show() if create new figure

if __name__ == '__main__':
    #made up data
    l1 = [1,2,3,4]
    l2 = [20,21,22,23]
    name = ['1990','1991','1992','1993']
    total_width, n = 0.8, 2
    width = total_width / n
    x = [i for i in range(0,4)]
    a = plt.bar(x, l1, width=width, label='Female', fc='b')
    for i in range(len(x)):
        x[i] = x[i] + width
    b = plt.bar(x, l2, width=width, label='Male', tick_label=name, fc='r')
    autolabel(a)
    autolabel(b)
    plt.xlabel('Year')
    plt.ylabel('Numbers')
    plt.title('Numbers by Gender')
    plt.legend()
    callback = Index()
    axnext = plt.axes([0.81, 0.05, 0.1, 0.075])
    bnext = Button(axnext, 'Male')
    bnext.on_clicked(callback.getmale)
    plt.show()

0 个答案:

没有答案