我正在处理ML项目,并且希望实时(相对)显示具有适应度函数的图表。
我正在使用this SO answer中的代码,只要该图表显示在matplotlib窗口中,它就可以正常工作。只要将其添加到页面中,它就会变成静态图像。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
fig, ax = plt.subplots()
max_x = 5
max_rand = 10
x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))
def init(): # give a clean slate to start
line.set_ydata([np.nan] * len(x))
return line,
def animate(i): # update the y values (every 1000ms)
line.set_ydata(np.random.randint(0, max_rand, max_x))
return line,
ani = animation.FuncAnimation(
fig, animate, init_func=init, interval=1000, blit=True, save_count=10)
st.pyplot(plt)
任何想法如何为图表设置动画?不必是matplotlib。
答案 0 :(得分:2)
我收到了answer on the streamlit forum,所以我只是在这里复制更新的代码
import matplotlib.pyplot as plt
import numpy as np
import streamlit as st
import time
fig, ax = plt.subplots()
max_x = 5
max_rand = 10
x = np.arange(0, max_x)
ax.set_ylim(0, max_rand)
line, = ax.plot(x, np.random.randint(0, max_rand, max_x))
the_plot = st.pyplot(plt)
def init(): # give a clean slate to start
line.set_ydata([np.nan] * len(x))
def animate(i): # update the y values (every 1000ms)
line.set_ydata(np.random.randint(0, max_rand, max_x))
the_plot.pyplot(plt)
init()
for i in range(100):
animate(i)
time.sleep(0.1)