Matplotlib is an amazing visualization library in Python. And, Streamlit is an amazing technology that turns data scripts into shareable web apps in minutes.
The main agenda of the article is to make you learn “How to embed Matplotlib visuals into Streamlit web app”.
Lets first set up the environment:
Note: All commands are for Windows — command prompt.
Install streamlit, yfinance and matplotlib pacakges.
Let’s add a new page, named ‘Bar Plot’, and plot a bar graph on a new page.
First add the name of the page into the sidebar.selectbox(), inorder to add page name in dropdown menu.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Bar Plot" # New page name
]
)
bar_chart()
Bar graph for the new page:
Pyplot have bar() function to draw bar graphs.
The bar() function takes arguments that describes the layout of the bars.
The values of the X and Y axes are represented by the first and second argument as arrays, passed to the bar function.
The figure() function in pyplot module of matplotlib library is used to create a new figure, a blank sheet of size- M * N, where M & N are passed as a parameter.
Xlabel, ylable and title are used to name X-axis, Y-axis and the plot respectively.
def bar_chart():
#Creating the dataset
data = {'C':20, 'C++':15, 'Java': 30, 'Python':35}
Courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
plt.bar(Courses, values)
plt.xlabel("Programming Environment")
plt.ylabel("Number of Students")
plt.title("Students enrolled in different courses")
st.pyplot(fig)
Output
Horizontal Bar Graph
Now let’s add a ‘Horizontal Bar Graph’ in our Streamlit application.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Horizontal Bar Graph", #New page
]
)
horizontal_bar_graph()
To plot horizontal bar graph, pyplot.barh() is used.
def horizontal_bar_graph():
#Creating the dataset
data = {'C':20, 'C++':15, 'Java': 30, 'Python':35}
Courses = list(data.keys())
values = list(data.values())
fig = plt.figure(figsize = (10, 5))
plt.barh(Courses, values)
plt.xlabel("Number of Students")
plt.ylabel("Programming Environment")
plt.title("Students enrolled in different courses")
st.pyplot(fig)
Output
Scatter plot
Adding a new page for Scatter Plot in our Streamlit application.
We can use numpy array to create the data set. Install numpy by following command:
pip install numpy
After installation import the numpy module.
import numpy as np
Pyplot have scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the same length, one for the values of the x-axis, and one for values on the y-axis.
def scatter_plot():
#Create numpy array for the visualisation
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
fig = plt.figure(figsize=(10, 4))
plt.scatter(x, y)
st.balloons()
st.pyplot(fig)
Output
Histogram
A histogram is a graph showing frequency distributions.
Histogram is a graph showing the number of observations within each given interval.
Adding a new page for the histogram in our Streamlit web app.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Histogram" # New Page
]
)
histogram()
In Matplotlib, the hist() function is used to create histograms.
The hist() function will use an array of numbers to create a histogram, the array is passed to the function as an argument.
numpy.random.normal() is used to draw random samples from a normal (Gaussian) distribution.
subplots() function allows to draw multiple plots in one figure.
Add a new page for SubPlot in the app.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Sub Plot" # New Page
]
)
subPlot()
The subplots() function takes three arguments that describes the layout of the figure.
The layout is organized in rows and columns, which are represented by the first and second argument.
The third argument represents the index of the current plot.
For example:
plt.subplot(1, 2, 1)
#the figure has 1 row, 2 columns, and this plot is the first plot.
plt.subplot(1, 2, 2)
#the figure has 1 row, 2 columns, and this plot is the second plot.