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
andmatplotlib
pacakges.
pip install streamlit
pip install yfinance
pip install matplotlib
Yfinance is a python package that enables us to fetch historical market data from Yahoo Finance API in a Pythonic way.
Now we are good to start creating our first visual in Streamlit.
- Importing modules
import yfinance as yf
import streamlit as st
import matplotlib.pyplot as plt
Most of the Matplotlib utilities lies under the
pyplot
submodule, and are usually imported under theplt
alias.
Setting up our homepage window of Streamlit app:
st.sidebar.selectbox()
, let us customize the option within selectbox (i.e drop down menu).
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Homepage"
]
)
if page == "Homepage":
homepage()
- tickerSymbol : Ticker Symbol is a name of the company by which is get listed in any stock exchange. ‘TSLA’ is ticker symbol Tesla motors.
- yf.Ticker: Ticker method gives all the market data for the respective tickerSymbol.
- ticker.history : Gives data frame that we are going to use in creating the visual.
st.line_chart()
is for creating line chart.
def homepage():
st.write("""
# Simple Stock Price App
### Shown are the stock **closing price** and **volume** of _**Tesla !**_ ###
#""")
tickerSymbol = 'TSLA'
tickerData = yf.Ticker(tickerSymbol)
tickerDf = tickerData.history(period='id', start='2010-5-31', end='2021-5-31')
st.line_chart(tickerDf.Close)
- The driver code
if __name__ == "__main__":
main()
Command to run the streamlit app
streamlit run app.py
app.py is the file name of the Streamlit app that we have created so far.
Output
Bar graph
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.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Scatter Plot"
]
)
scatter_plot()
- 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.
def histogram():
x = np.random.normal(170, 10, 250)
fig = plt.figure(figsize=(10, 4))
plt.hist(x)
st.balloons()
st.pyplot(fig)
Output
Pie chart
Adding a new page for the PieChart in our Streamlit web app.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Pie Chart" # New Page
]
)
pieChart()
- Pyplot have
pie()
function to draw pie charts. - Add labels to the pie chart with the
label
parameter. - The
label
parameter must be an array with one label for each section.
def pieChart():
x = np.array([35, 25, 25, 15])
mylabels = ["Python", "JavaScript", "C++", "C"]
fig = plt.figure(figsize=(10, 4))
plt.pie(x, labels = mylabels)
st.balloons()
st.pyplot(fig)
Output
Sub Plots
subplots()
function allows to draw multiple plots in one figure.
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.
def subPlot():
st.header("Sub Plots")
st.balloons()
fig = plt.figure(figsize = (10, 5))
#Plot 1
data = {'C':15, 'C++':20, 'JavaScript': 30, 'Python':35}
Courses = list(data.keys())
values = list(data.values())
plt.xlabel("Programming Environment")
plt.ylabel("Number of Students")
plt.subplot(1, 2, 1)
plt.bar(Courses, values)
#Plot 2
x = np.array([35, 25, 25, 15])
mylabels = ["Python", "JavaScript", "C++", "C"]
plt.subplot(1, 2, 2)
plt.pie(x, labels = mylabels)
st.pyplot(fig)
Output
How to control multiple charts
- Multiple pages can also be added to the streamlit application, just add values into
streamlit.selectbox()
.
def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Homepage",
"Bar Plot",
"Horizontal Bar Graph",
"Scatter Plot",
"Histogram",
"Pie Chart",
"Sub Plot"
]
)
#First Page
if page == "Homepage":
homepage()
#Second Page
elif page == "Bar Plot":
bar_chart()
#Third Page
elif page == "Horizontal Bar Graph":
horizontal_bar_graph()
#Fourth Page
elif page == "Scatter Plot":
scatter_plot()
#Fifth page
elif page == "Histogram":
histogram()
#Sixth Page
elif page == "Pie Chart":
pieChart()
elif page == "Sub Plot":
subPlot()
streamlit.selectbox()
.def main():
page = st.sidebar.selectbox(
"Select a Page",
[
"Homepage",
"Bar Plot",
"Horizontal Bar Graph",
"Scatter Plot",
"Histogram",
"Pie Chart",
"Sub Plot"
]
)
#First Page
if page == "Homepage":
homepage()
#Second Page
elif page == "Bar Plot":
bar_chart()
#Third Page
elif page == "Horizontal Bar Graph":
horizontal_bar_graph()
#Fourth Page
elif page == "Scatter Plot":
scatter_plot()
#Fifth page
elif page == "Histogram":
histogram()
#Sixth Page
elif page == "Pie Chart":
pieChart()
elif page == "Sub Plot":
subPlot()