Gleeson9 Gleeson9 - 1 year ago 101
Python Question

Matplotlib - Updating bar graph with positive and negative values

I am using the method described in this answer to dynamically update a bar graph. The bar graph I want however should show values coming from the zero-point rather than the bottom of the graph. This is my bar initialisation code:

oxBar =, 200, bottom=-100, width=1)

And I want to be able to update my graph positively and negatively from the zero point. However using the method in the link above I can only get it to go to a height from the bottom of the graph rather than the zero-point. For example, inputting -50 should draw the bar from 0 to -50, however instead it is drawing the bar from -100 to -50 instead.

Answer Source

Matplotlib as default autosizes plot but you can set ylim to have constant size/height and then 0 can be always in middle.


import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random

def animate(frameno):
    x = random.randint(-200, 200)
    n = [x, -x]

    for rect, h in zip(rects, n):

    return rects

# --- init ---

fig, ax = plt.subplots()
rects =[0,1], [0,0], width=1)
plt.ylim([-200, 200])

ani = animation.FuncAnimation(fig, animate, blit=True,
                              interval=100, frames=100, repeat=False)

enter image description here

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download