使用按钮小部件创建交互式Matplotlib直方图



我正在尝试使用Matplotlib来创建一个交互式图形。我希望每次按下图形按钮时都能浏览一组图形。然而,即使我的按钮似乎工作,我不能得到图形重新绘制。我看了网上的例子,但还没能看到我错过了什么。

import matplotlib.pyplot as plt
from matplotlib.widgets import Button
import numpy as np
curr = 0
avgData = None
...
def prev(event):
    #Use '<' button to get prior histogram
    global curr
    curr -= 1
    reset()
def next(event):
    #Use '>' button to get next histogram
    global curr
    curr += 1
    reset()

def reset():
    #Get data for new graph and draw/show it
    global curr
    global avgData
    #Stay within bounds of number of histograms
    if curr < 0:
        curr = 0
    elif curr >= len(avgData):
        curr = len(avgData) - 1
    #Get info for new histogram
    bins, hist, hist2, barWidth = getHistParams(avgData[curr])
    #Verify code got here and obtained data for next histogram
    f=open('reset.txt','a')
    f.write(str(curr))
    f.write(str(hist2))
    f.write("n==========================================================n")
    f.close()
    #Try to draw
    plt.figure(1)
    rects = plt.bar(bins,hist2,width=barWidth,align='center')
    plt.draw()
def plotHistGraphs(avg):
    #Create initial plot
    #Get initial data
    bins, hist, hist2, calcWidth = getHistParams(avg)
    #Create plot 
    plt.figure(1)
    rects = plt.bar(bins,hist2,width=calcWidth,align='center')
    plt.xlabel("Accuracy of Classifiers")
    plt.ylabel("% of Classifiers")
    plt.title("Histogram of Classifier Accuracy")
    #Create ">"/"Next" Button
    histAxes1 = plt.axes([0.055, 0.04, 0.025, 0.04])
    histButton1 = Button(histAxes1, ">", color = 'lightgoldenrodyellow', hovercolor = '0.975')
    histButton1.on_clicked(next)
    #Create "<"/"Prev" Button
    histAxes2 = plt.axes([0.015, 0.04, 0.025, 0.04])
    histButton2 = Button(histAxes2, "<", color = 'lightgoldenrodyellow', hovercolor = '0.975')
    histButton2.on_clicked(prev)
    plt.show()

我已经试验了plt的各种排列。秀,plt。画和画。离子,但似乎仍然不能让这个工作。我在函数reset中创建的输出文件显示,按钮正在工作,并且我正在获取所需的数据。我就是没法把旧的直方图去掉,然后在原来的地方画出新的直方图。

如果您有任何帮助/建议,我将不胜感激。

在画新图形之前需要清除旧图形。对于plt.cla()plt.clf()也可以这样做

最新更新