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

时间:2014-07-21 19:28:03

标签: python 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.show,plt.draw和plt.ion的各种排列,但似乎仍然无法实现这一点。我在函数reset中创建的输出文件显示按钮正在工作,我正在获取所需的数据。我不能让旧的直方图消失,并在其位置绘制新的直方图。

非常感谢任何帮助/建议。

1 个答案:

答案 0 :(得分:0)

在绘制新图之前,您需要清除旧图。您可以使用plt.cla()plt.clf()

执行此操作