Gleeson9 Gleeson9 - 18 days ago 9
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 = aBar.bar(0, 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

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

Example

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):
        rect.set_height(h)

    return rects

# --- init ---

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

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

enter image description here