Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Updating a matplotlib bar graph?

I have a bar graph which retrieves its y values from a dict. Instead of showing several graphs with all the different values and me having to close every single one, I need it to update values on the same graph. Is there a solution for this?

like image 595
M_Moose Avatar asked Feb 28 '12 21:02

M_Moose


People also ask

How do I update a bar graph in matplotlib?

Create a new figure or activate an existing figure. Make a list of data points and colors. Plot the bars with data and colors, using bar() method. Using FuncAnimation() class, make an animation by repeatedly calling a function, animation, that sets the height of the bar and facecolor of the bars.

How do you update a PLT plot?

After that we are initializing GUI using plt. ion() function, now we have to create a subplot. After that, we are running a for loop and create new_y values which hold our updating value then we are updating the values of X and Y using set_xdata() and set_ydata().

How do I customize matplotlib?

There are three ways to customize Matplotlib: Setting rcParams at runtime. Using style sheets. Changing your matplotlibrc file.


2 Answers

Here is an example of how you can animate a bar plot. You call plt.bar only once, save the return value rects, and then call rect.set_height to modify the bar plot. Calling fig.canvas.draw() updates the figure.

import matplotlib
matplotlib.use('TKAgg')
import matplotlib.pyplot as plt
import numpy as np

def animated_barplot():
    # http://www.scipy.org/Cookbook/Matplotlib/Animations
    mu, sigma = 100, 15
    N = 4
    x = mu + sigma*np.random.randn(N)
    rects = plt.bar(range(N), x,  align = 'center')
    for i in range(50):
        x = mu + sigma*np.random.randn(N)
        for rect, h in zip(rects, x):
            rect.set_height(h)
        fig.canvas.draw()

fig = plt.figure()
win = fig.canvas.manager.window
win.after(100, animated_barplot)
plt.show()
like image 108
unutbu Avatar answered Sep 22 '22 18:09

unutbu


I've simplified the above excellent solution to its essentials, with more details at my blogpost:

import numpy as np
import matplotlib.pyplot as plt

numBins = 100
numEvents = 100000

file = 'datafile_100bins_100000events.histogram'
histogramSeries = np.loadtext(file)

fig, ax = plt.subplots()
rects = ax.bar(range(numBins), np.ones(numBins)*40)  # 40 is upper bound of y-axis 

for i in range(numEvents):
    for rect,h in zip(rects,histogramSeries[i,:]):
        rect.set_height(h)
    fig.canvas.draw()
    plt.pause(0.001)
like image 38
stochashtic Avatar answered Sep 22 '22 18:09

stochashtic