'Streamlit: plot mathematical function dynamically with parameters

I am looking for a solution to plot dynamically mathematical function in 2D on a web page made with Streamlit. For example I would like to plot a normal distribution and have two sliders to set the mean and st dev of the distribution. I am looking for something that would continuously update. There are plenty of solution to plot static graphic function. Do you have any clue of which lib I should use ? I did not found example for this topic on internet. Nor specific solution. Would it be possible with plotta.js ? But I am sure some did have the same need as me. Would plottly.js work for this ? (I do not want the backend to compute the functions). If anyone as a code pen, that would be perfect.

Cheers



Solution 1:[1]

Sample code using matplotlib.

import numpy as np
import matplotlib.pyplot as plt
import streamlit as st
 
x = np.linspace(-10,10,100)
 
def normal_dist(x , mean , sd):
    prob_density = np.exp(-0.5*((x-mean)/sd)**2) / np.sqrt(np.pi * sd**2)
    return prob_density
 
mean = st.slider(label='input mean', min_value=0., max_value=100., value=4.)
sd = st.slider(label='input std dev', min_value=0.1, max_value=100., value=4.)
 
pdf = normal_dist(x,mean,sd)

fig, ax = plt.subplots()
plt.plot(x, pdf , color = 'blue')
plt.xlabel('Data points')
plt.ylabel('Probability Density')
st.pyplot(fig)

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ferdy