0

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.

Community
  • 1
  • 1
Jordan Gleeson
  • 531
  • 1
  • 4
  • 12
  • why don't use `bottom=0` ? `plt.bar(0, -50, bottom=0, width=1)` ? – furas Nov 23 '16 at 02:15
  • I could, however I want to have the graph origin from the midpoint of the graph, and using this method always does it from the bottom instead, so this doesn't fix the issue. – Jordan Gleeson Nov 23 '16 at 02:18
  • but it draws from 0 to -50 - ie. `plt.bar([0,1,2], [-100, -50,100], bottom=0, width=1)` draws from 0 to -100 and from 0 to 100 and 0 is in the middle. Probably you need other properties to set plot size. – furas Nov 23 '16 at 02:23
  • Ah yes, I see what your saying. That works when you don't have to change the data values, but when you use `rect.set_height(h)` (as seen in the linked question) it only seems to draw from the 'bottom' – Jordan Gleeson Nov 23 '16 at 02:28
  • Maybe try `plt.ylim([-200,200])` – furas Nov 23 '16 at 02:28
  • Sorry @furas I had the wrong question linked. Just fixed it then. – Jordan Gleeson Nov 23 '16 at 02:30
  • try this http://pastebin.com/cvNmBZhS – furas Nov 23 '16 at 02:40
  • Great, thanks. That did actually work. Feel free to post it as an answer so I can check this as answered. – Jordan Gleeson Nov 23 '16 at 02:57

1 Answers1

1

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

furas
  • 134,197
  • 12
  • 106
  • 148