user1245262
user1245262

Reputation: 7505

Creating interactive Matplotlib histograms with Button widget

I'm trying to use Matplotlib to create an interactive graph. I would like to flip through a set of graphs each time I press a graphical button. However, even though my buttons seem to work, I can't get graphs to replot. I've looked at online examples but haven't been able to see what I'm missing.

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

I've experimented with various permutations of plt.show, plt.draw and plt.ion, but still can't seem to get this to work. The output file I've created in the function, reset, shows that the Buttons are working and that I'm getting the data I need. I just can't get the old histogram to go away and to plot the new histogram in its place.

Any help/suggestions would be very much appreciated.

Upvotes: 0

Views: 1115

Answers (1)

Shashank Agarwal
Shashank Agarwal

Reputation: 2804

You need to clear the old figure before drawing the new one. You can do that with plt.cla() and plt.clf()

Upvotes: 1

Related Questions