0

I'm trying to update the barchart with new data. I cant use FuncAnimation, so I would like to use a for loop. I'm using Python through Jupyter

what am I doing wrong? Thanks

import matplotlib.pyplot as plt


data1 = [6,7,5,6,8,6,9,7]
data2 = [2,3,5,6,7,8,4,2]
data3 = [4,2,1,3,5,6,6,7]
data4 = [1,6,5,4,3,2,11,9]
data5 = [6,7,5,6,8,6,9,7]
data6 = [2,3,5,6,7,8,4,2]
data7 = [4,2,1,3,5,6,6,7]
data8 = [1,6,5,4,1,2,11,9]
data = [data1,data2,data3,data4,data5,data6,data7,data8]
name = "area1"

fig = plt.figure(figsize=(14,8))
fig.canvas.manager.set_window_title("area_1")


plt.ion()

ax = plt.axes()
ax.set_facecolor("#BCECE0")
plt.title(name, color="#F652A0")

rects = plt.bar(range(len(data)), 0, tick_label=range(len(data)), color="#4C5270")
plt.legend()
plt.show()


for i in range(8):
   for rect,h in zip(rects,data[i]):
      rect.set_height(h)
   fig.canvas.draw()
   plt.pause(1)

1 Answers1

0

I would suggest adapting some of the ideas from here. For instance, in the code below, I update the bar plot at each of the 8 frames by passing the value of each bar with rect.set_height(h). See code below:

import matplotlib
import matplotlib.pyplot as plt
import numpy as np
%matplotlib notebook

data1 = [6,7,5,6,8,6,9,7]
data2 = [2,3,5,6,7,8,4,2]
data3 = [4,2,1,3,5,6,6,7]
data4 = [1,6,5,4,3,2,11,9]
data5 = [6,7,5,6,8,6,9,7]
data6 = [2,3,5,6,7,8,4,2]
data7 = [4,2,1,3,5,6,6,7]
data8 = [1,6,5,4,1,2,11,9]
data = [data1,data2,data3,data4,data5,data6,data7,data8]  

fig,ax = plt.subplots()
name = "area1"
ax.set_facecolor("#BCECE0")
plt.title(name, color="#F652A0")

N_bars=len(data[0])
rects = plt.bar(range(N_bars), data[0],  align ='center',color="#4C5270")
plt.ylim([0,np.amax(data)])
for i in range(N_bars):
    dat=data[i]
    for rect, h in zip(rects, dat):
        rect.set_height(h)
        
    fig.canvas.draw()
    plt.savefig('fig-'+str(i)+'.png')
    plt.pause(1)

plt.show()

And the output gives:

enter image description here

jylls
  • 4,395
  • 2
  • 10
  • 21
  • Thank you very much. Now the problem is that it works on Pycharm but not in Jupyter. wehn I run in Jupiter its just adding new graphs below that are not updated – aviv avinoam Dec 08 '21 at 06:40
  • You need to add `%matplotlib notebook` for this to work on jupyter notebook. See edit of my answer. – jylls Dec 08 '21 at 13:36