使用新数据更新条形图



我重用这个线程的第一个解决方案:用新数据更新线图。特别是,这个代码块:

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()

现在我想做同样的事情,但绘制条形图而不是折线图:

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()

上面的代码不会更新图表。如何以与上面的折线图相同的方式更新条形图?

更新:遵循@r-初学者的建议:

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()

我收到一个错误ValueError: setting an array element with a sequence.

我想这和新的for循环有关吧?

条形图的高度可以由set_height((指定,因此需要修改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()

最新更新