Ah, unfortunately Matplotlib relies on generating static images at every Streamlit script rerun, so the FuncAnimation will also somewhere on the line be transformed to static animations, that doesnāt make it very friendly for live data. I usually go for Plotly, Altair or ECharts for dynamic plotting of data in the browser.
Then I would save the latest n points of live data in Streamlit cache and plot it on every tick.
Hi @Zane_Venter, I agree with @fanilo, but in case you want to follow in this direction, Iāve managed to show the animation, hope it is good for you:
(Edit: I had some lines missing, here is the corrected code )
import streamlit as st
import streamlit.components.v1 as components
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
def func(t, line):
t = np.arange(0,t,0.1)
y = np.sin(t)
line.set_data(t, y)
return line
fig = plt.figure()
ax = plt.axes(xlim=(0, 100), ylim=(-1.2, 1.22))
redDots = plt.plot([], [], 'ro')
line = plt.plot([], [], lw=2)
# Creating the Animation object
line_ani = animation.FuncAnimation(fig, func, frames=np.arange(1,100,0.1), fargs=(line), interval=100, blit=False)
#line_ani.save(r'Animation.mp4')
#HtmlFile = line_ani.to_html5_video()
with open("myvideo.html","w") as f:
print(line_ani.to_html5_video(), file=f)
HtmlFile = open("myvideo.html", "r")
#HtmlFile="myvideo.html"
source_code = HtmlFile.read()
components.html(source_code, height = 900,width=900)
Thank you so much. This definitely helped me to get an better Idea of the solution, its still not 100% there but progress is progress and the guidance really helped me!
I have combined both recommendations, and its working with streamlit.
Thanks first for everything in this thread, as I have gotten quite far with visualizing matplotlib animations in streamlit.
Iām trying to use streamlit to make a sort algorithm visualizer, where I am just using the rather simple bubble sort algo to test.
The problem Iām having is that the code posted works and works in streamlit but only interates once through the sort function, thus sorting only one number in the array. Iām new to matplotlib and streamlit, so I canāt tell if there is a way to create my own animation, or get FuncAnimation to behave differently (I read the docs and seems pretty straightforward as a function repeater).
Any pointers are appreciated. Thanks.
import streamlit as st
import streamlit.components.v1 as components
import time
import numpy as np
import scipy as sp
import random
import matplotlib.pyplot as plt
import matplotlib.animation as anim
# Sorting Algorithms.
def bubble_sort(arr):
for i in range(len(arr) - 1, 0, -1):
for j in range(i):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
yield arr
n = 100 # int(input("Enter the number of elements: "))
array = [i + 1 for i in range(n)]
algo = bubble_sort(array) # int(input(f"Choose algorithm: \n 1.Bubble: "))
random.shuffle(array)
title = "Bubble Sort"
# if alg == 1:
# title = "Bubble Sort"
# algo = bubble_sort(array)
# Initialize fig
fig, ax = plt.subplots()
ax.set_title(title)
bar_rec = ax.bar(range(len(array)), array, align='edge')
ax.set_xlim(0, n)
ax.set_ylim(0, int(n * 1.06))
text = ax.text(0.02, 0.95, "0", transform=ax.transAxes)
epochs = [0]
def update_plot(array, rec, epochs):
for rec, val in zip(rec, array):
rec.set_height(val)
epochs[0] += 1
text.set_text("No.of operations :{}".format(epochs[0]))
anima = anim.FuncAnimation(fig, update_plot, fargs=(bar_rec, epochs), frames=algo, interval=1, repeat=False)
# plt.show()
# st.pyplot(plt)
components.html(anima.to_jshtml(), height=1000)
I figured it out. Itās a matplotlib.funcanimation parameter āsave_countā which sets the number of saved frames and nothing to do with streamlit. Streamlit rocks to be able to do this so easily, despite my newbie difficulties.
Thanks for stopping by! We use cookies to help us understand how you interact with our website.
By clicking āAccept allā, you consent to our use of cookies. For more information, please see our privacy policy.
Cookie settings
Strictly necessary cookies
These cookies are necessary for the website to function and cannot be switched off. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms.
Performance cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us understand how visitors move around the site and which pages are most frequently visited.
Functional cookies
These cookies are used to record your choices and settings, maintain your preferences over time and recognize you when you return to our website. These cookies help us to personalize our content for you and remember your preferences.
Targeting cookies
These cookies may be deployed to our site by our advertising partners to build a profile of your interest and provide you with content that is relevant to you, including showing you relevant ads on other websites.