[英]Changing graphs in real-time using matplotlib
這是代碼。
import matplotlib.pyplot as plt
import random
x = []
y = []
for i in range(10):
x.append(i)
y.append(random.randint(0,100))
graph = plt.bar(x,y)
plt.show()
每當我更改 y 的任何值時,比如說 y[4] = 7 ,然后我希望它反映在圖表中。 我希望該圖表移動。
我嘗試為此搜索解決方案,但沒有一個對我有用。
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import random
x = []
y = []
for i in range(10):
x.append(i)
y.append(random.randint(0,100))
fig, ax = plt.subplots()
bar, = ax.plot(x,y)
def animate(i):
x = []
y = []
for i in range(10):
x.append(i)
y.append(random.randint(0,100))
bar.set_xdata(x)
bar.set_ydata(y)
return bar,
animation = FuncAnimation(fig, animate, interval = 1000)
plt.show()
我想要類似的結果,但以條形圖的形式。 任何幫助表示贊賞。
條形圖中顯示的數據未鏈接到列表中的數據。 沒有附加到列表的偵聽器讓 pyplot 知道列表何時被修改。
您將需要手動更改條形的高度。 您可以通過獲取graph
object 的子項(條形列表)並更新條形高度來完成此操作。
請注意,下面的代碼有效是因為x
和條的索引相同。 如果x
從 1 開始或者 a 是range(0, 100, 10)
,代碼會變得更加復雜。
import matplotlib.pyplot as plt
import random
# turn on interactive graphing
plt.ion()
x = []
y = []
for i in range(10):
x.append(i)
y.append(random.randint(0,100))
graph = plt.bar(x,y)
plt.show()
y[4] = 7
graph.get_children()[4].set_height(7)
終於得到了我想要的
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import random
X = []
Y = []
for i in range(20):
Y.append(random.randint(1, 100))
X.append(i)
fig, ax = plt.subplots(figsize=(10, 6))
ax.bar(X, Y, color="#ff7f7f")
ax.set_yticks([])
ax.set_xticks(X)
for number in range(len(Y)):
ax.text(number, Y[number], Y[number],
horizontalalignment='center', va="baseline", fontsize=13)
def draw_barchart(year):
ax.clear()
X.clear()
Y.clear()
for i in range(20):
Y.append(random.randint(1, 100))
X.append(i)
ax.bar(X, Y, color="#ff7f7f")
ax.set_yticks([])
ax.set_xticks(X)
ax.set_yticks([])
ax.set_xticks(X)
for number in range(len(Y)):
ax.text(number, Y[number], Y[number], horizontalalignment='center', va="baseline", fontsize=13)
plt.box(False)
animator = animation.FuncAnimation(fig, draw_barchart, interval=1000)
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.