0

I am reusing the first solution from this thread: updating line plot with new data. Particularly, this code chunk:

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 6*np.pi, 100)
y = np.sin(x)


plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
line1, = ax.plot(x, y, 'r-') # Returns a tuple of line objects, thus the comma

for phase in np.linspace(0, 10*np.pi, 500):
    line1.set_ydata(np.sin(x + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()

Now I want do the same, but plotting a bar chart instead of the line chart:

x2 = np.linspace(0, 6 * np.pi, 100)
y2 = np.sin(x2)


plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
bar1, = ax.bar(x2, y2, 0.01)

for phase in np.linspace(0, 10 * np.pi, 500):
    bar1.datavalues(np.sin(x2 + phase))
    fig.canvas.draw()
    fig.canvas.flush_events()

The code above does not update the chart. How do I update a bar chart in the same way as the line chart above is being updated?

Update: follow @r-beginners suggestion:

x2 = np.linspace(0, 6 * np.pi, 100)
y2 = np.sin(x2)


plt.ion()

fig = plt.figure()
ax = fig.add_subplot(111)
bar1 = ax.bar(x2, y2, 0.01)

for  rect, phase in zip(bar1, np.linspace(0, 10 * np.pi, 500)):
    bar1.datavalues = np.sin(x2 + phase)
    rect.set_height(bar1.datavalues)
    fig.canvas.draw()
    fig.canvas.flush_events()

I got an error ValueError: setting an array element with a sequence.

I guess it got to do with the new for loop?

Tristan Tran
  • 1,351
  • 1
  • 10
  • 36

1 Answers1

0

The height of the bar chart can be specified by set_height(), so you need to modify bar1.datavalues.

for rect, phase in zip(bar1, np.linspace(0, 10 * np.pi, 500)):
    rect.set_height(phase)
    fig.canvas.draw()
    fig.canvas.flush_events()
r-beginners
  • 31,170
  • 3
  • 14
  • 32