Plotly is an open-source graphing library that makes interactive, publication-quality graphs. Plotly is a very helpful tool for understanding and visualizing data. Plotly supports various plots such as scatter plots, pie charts, line charts, bar charts, box plots, histograms, etc.
Streamlit is an amazing technology that turns data scripts into shareable web apps in minutes.
Installation
pip install plotly
Inside the Plotly module
Plotly.graph_objects()
– function lets us plot various graphs and charts.
Pie Chart
Required modules
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
Creating data Set
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
Either own dataset can be created or taken from any CSV file. Using pandas.read_csv()
.
countries=['India', 'Australia',
'Japan', 'America',
'Russia']
values = [4500, 2500, 1053, 500,
3200]
Now creating a figure and plotting the pie chart into the figure.
- Plotly has
Figure()
function to create a figure. Figure is like a blank Sheet in which we create our actual plots. - And, Plotly has
Pie()
function to create a pie chart, which takes labels and values as the parameter and two optional hoverinfo and textinfo parameters to load text onto the pie chart.
fig = go.Figure(
go.Pie(
labels = countries,
values = values,
hoverinfo = "label+percent",
textinfo = "value"
))
Streamlit.header()
– function to create heading in our streamlit app.Streamlit.plotly_chart()
– function allows to load the figure into the streamlit app.
st.header("Pie chart")
st.plotly_chart(fig)
Full implementation would be like this:
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
#Data Set
countries=['India', 'Australia',
'Japan', 'America',
'Russia']
values = [4500, 2500, 1053, 500,
3200]
#The plot
fig = go.Figure(
go.Pie(
labels = countries,
values = values,
hoverinfo = "label+percent",
textinfo = "value"
))
st.header("Pie chart")
st.plotly_chart(fig)
Command to run the streamlit application
streamlit run app.py
app.py is the file name of the python file we have created so far.
Output
Donut Chart
For Donut-chart, Plotly module has a separate sub-module named express()
.
import plotly.express as px
Data Set
data_frame = {'India': 4500,
'Australia': 2500,
'Japan': 1053,
'America': 500,
'Russia': 3200 }
Plotly express has pie()
– function to plot a Donut chart. pie()
takes parameter as follows:
- hole : hole an integer value that specifies the radius of the hole in the donut.
- labels : labels takes a list — that to plot in a chart.
- names : list to create the index of the labels in the plot.
fig = px.pie(
hole = 0.2,
labels = data_frame.values(),
names = data_frame.keys(),
)
st.header("Donut chart")
st.plotly_chart(fig)
Output
Scatter Plot
Plotly have express.scatter()
function to create a scatter plot. The scatter() function takes two list’s as parameters to plot in X and Y axes.
Data Set
Using NumPy module to create demo data set.
import numpy as np
np.random.randint(X, Y, Z)
– function returns an array of length Z, consisting integers between X and Y (exclusive of Y).
value_x = np.random.randint(1, 101, 100)
value_y = np.random.randint(1, 101, 100)
fig = px.scatter(
x = value_x,
y = value_y,
)
Output
Line Plot
Plotly have express.line()
function to create a line plot. The line() function takes two list’s as parameters to plot in X, Y axes OR You can name the data set and put the columns of the data set on the X & Y axes. There’s an optional parameter called title, a title for the plot.
Data Set
A Pandas Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns.
df = pandas.DataFrame(dict(
X_axis = [i for i in range(100)],
Y_axis = np.random.randint(10, 50, 100)
))
fig = px.line(
df, #Data Frame
x = "X_axis", #Columns from the data frame
y = "Y_axis",
title = "Line frame"
)
fig.update_traces()
function allows us to change visual properties to plot like colour, etc.
fig.update_traces(line_color = "maroon")
st.plotly_chart(fig)
Full implementation would be like this:
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
#Data Set
df = pandas.DataFrame(dict(
X_axis = [i for i in range(100)],
Y_axis = np.random.randint(10, 50, 100)
))
#The plot
fig = px.line(
df, #Data Frame
x = "X_axis", #Columns from the data frame
y = "Y_axis",
title = "Line frame"
)
fig.update_traces(line_color = "maroon")
st.plotly_chart(fig)
Output
Bar Graph
Similar to Line Plot, Plotly has express.bar()
function to create a bar graph. The bar()
function also takes two list’s as parameters to plot in X, Y axes OR a data set can be mentioned and data set’s columns can be used for the X & Y axes. There’s an optional parameter called title, a title for the plot.
Data Set
A Pandas Data frame is a two-dimensional data structure, i.e., data is aligned in a tabular fashion in rows and columns.
dict = {'X_axis': np.random.randint(10, 50, 20),
'Y_axis': [i for i in range(20)]}
df = pd.DataFrame(dict)
fig = px.bar(
df,
x = "X_axis",
y = "Y_axis",
title = "Bar Graph"
)
st.plotly_chart(fig)
Output
The bar() function also has one optional parameter to change the colour of the bars in the plot.
#Axis to color
color="X_axis",
fig = px.bar(
df,
x = "X_axis",
y = "Y_axis",
title = "Bar Graph",
color="X_axis",
)
st.plotly_chart(fig)
Output
Horizontal Bar Graph
Exactly similar to Bar graph, a horizontal bar graph can be created by changing the orientation of the plot. px.bar()
has an optional parameter to specify the orientation.
fig = px.bar(
df,
x = "X_axis",
y = "Y_axis",
title = "Horozontal Bar Graph",
color="X_axis",
orientation = 'h' #Optional Parameter
)
st.plotly_chart(fig)
Output
SubPlots in Plotly
Subplot enables to load the different plots(i.e bar graph, lin plot) side by side. Figures with subplots are created using the make_subplots()
– function from the plotly.subplots
– module.
from plotly.subplots import make_subplots
Side By Side Subplots
Creating a figure that includes two scatter plots that are side-by-side since there is 1 row and 2 columns in the subplot layout.
- Specify number of rows and columns
fig = make_subplots(rows=1, cols=2)
- Add plots inside the figure
#First SubPlot
fig.add_trace(
go.Scatter(
x=[1, 2, 3],
y=[4, 5, 6]),
row=1, col=1
)
#Second SubPlot
fig.add_trace(
go.Scatter(
x=[20, 30, 40],
y=[50, 60, 70]),
row=1, col=2
)
- Load the final figure into streamlit app.
st.plotly_chart(fig)
Output
Stacked Subplots
Creating a figure with subplots that are stacked on top of each other since there are 3 rows and 1 column in the subplot layout.
fig = make_subplots(rows=3, cols=1)
#First Subplot
fig.add_trace(go.Scatter(
x=[3, 4, 5],
y=[1000, 1100, 1200],
), row=1, col=1)
#Second SubPlot
fig.add_trace(go.Scatter(
x=[2, 3, 4],
y=[100, 110, 120],
), row=2, col=1)
#Third SubPlot
fig.add_trace(go.Scatter(
x=[0, 1, 2],
y=[10, 11, 12]
), row=3, col=1)
st.plotly_chart(fig)
Full implementation would be like this:
import streamlit as st
import pandas as pd
import plotly.graph_objects as go
fig = make_subplots(rows=3, cols=1)
#First Subplot
fig.add_trace(go.Scatter(
x=[3, 4, 5],
y=[1000, 1100, 1200],
), row=1, col=1)
#Second SubPlot
fig.add_trace(go.Scatter(
x=[2, 3, 4],
y=[100, 110, 120],
), row=2, col=1)
#Third SubPlot
fig.add_trace(go.Scatter(
x=[0, 1, 2],
y=[10, 11, 12]
), row=3, col=1)
st.plotly_chart(fig)
Output