Introduction to Streamlit Bar Charts
Do you want a quick and easy to create and share your data visualizations? If so, then Streamlit can be a great option!
This article is an introduction to Streamlit via its Bar Charts. This tutorial is going to help you learn Streamlit by walking you through incremental steps. It will create increasingly feature and visually rich bar charts.
Streamlit is an open-source data visualization framework. It generates web visualizations using the Python programming language.
It has easy-to-read documentation that currently does not include details of the more advanced visuals.
Streamlit calls these ‘data apps’.
It can be run locally on your machine or it can be hosted on Streamlit’s cloud service. A Streamlit data app can have a responsive user interface that controls graphs with form elements. It can be created with less than 100 lines of code.
Usually, web apps have hundreds more lines of code. They require you to use CSS, HTML, and JavaScript as well as probably need an understanding of some back-end programming language. So, Streamlit’s simplicity and rapid development time can be a boon to productivity.
This tutorial follows a graph example with the associated code that I created. It is hosted on Streamlit’s cloud here. It follows Its source code is on Github here.
The data it uses are small data sets that are supposed to represent monthly energy bills that a person might have. The Bar Chart groups the data by month and sums the price of the bill.
Streamlit Basic Bar Chart
While the streamlit bar chart is extremely easy to use, the Streamlit basic bar chart has limited configuration options.
It can be created just by passing in a data frame into the Streamlit’s st.bar_chart()
(st
is imported as streamlit) function.
The cost of this simplicity is that the chart configuration is very limited. You can not change the chart labels. You can change the chart color with the panda styler object. Many configuration options are missing like labeling the x-axis labels and sorting.
The built-in bar chart can be used for a quick visual of data. The limited control of its configurations probably will make it impractical to use it for more than a test visualization or demo.
Below is the code used to create the char below:
"Energy Costs By Month" chart_data = pd.DataFrame( [10,13, 11], columns=["Energy Costs"]) st.bar_chart(chart_data)
The good news is that it is possible to use other chart types in Streamlit like pyplot, Altair charts, plotly, Matplotlib, and bokeh.
These charts are just some of the examples of the charting libraries that can be used. These charts can also be used outside of Streamlit.
The simple streamlit bar chart is just a simplified extension of the Altair chart. You are just using a more complex and feature-rich version of the same chart that has a more in-depth and exposed API. The Altair charts allow the user to zoom in and out on them.
This tutorial will show how to use the highly configurable Altair Charts to create feature-rich bar charts.
Streamlit Altair Chart
Using Altair charts on Streamlit offers much more flexibility at the cost of some but not that much additional complexity.
For production graphs, you’ll probably have to use a graphing library such as Altair. Altair’s overall simplicity and robustness make it an excellent choice for a graphing library. Altair charts have great detailed documentation.
Streamlit Altair Bar Chart With Axis Labels
To understand what a chart is trying to say and what it can be important to have it labeled. The streamlit Altair chart accepts a data frame to its Chart constructor.
This allows for variables to be passed in to add to or change the chart’s initial formatting.
To create the labels first the bar chart is created by the mark_bar()
function. , which is what creates the bar chart, then an encoding function with the passed-in parameters of the access labels, which are y
and x
.
The Altair documentation states that the encodings ‘map properties of the data to visual properties to effectively communicate information.’
These encodings are used for labeling, specifying chart data types, and changing colors. The common data types for the bar chart are quantitative Q, nominal, which is an ordered category O, and O ordinal which is a discrete ordered quantity.
You can see it in the function below in the creation of the bar chart. Below is the code used to create the chart:
"Energy Costs By Month" source = pd.DataFrame({ 'Price ($)': [10, 15, 20], 'Month': ['January', 'February', 'March'] }) bar_chart = alt.Chart(source).mark_bar().encode( y='Price ($):Q', x='Month:O', ) st.altair_chart(bar_chart, use_container_width=True)
Streamlit Altair Stacked Bar Charts
First, to create a stacked bar chart you must make sure that the data frame that you are passing in is in the right format for the stacked bar chart.
The chart must have a category that is common between different rows. These common categories are put into stacks. These rows will be used to create the stacks on each bar.
Below is a data frame that can be used in the stacked charts.
In this tutorial wherever the energy_source
variable below is the data frame that is being used.
energy_source = pd.DataFrame({ "EnergyType": ["Electricity","Gasoline","Natural Gas","Electricity","Gasoline","Natural Gas","Electricity","Gasoline","Natural Gas"], "Price ($)": [150,73,15,130,80,20,170,83,20], "Date": ["2022-1-23", "2022-1-30","2022-1-5","2022-2-21", "2022-2-1","2022-2-1","2022-3-1","2022-3-1","2022-3-1"] })
The common category in the below energy_source
data frame is “EnergyType”.
Secondly, you must add colors between the groups. This is done by the color parameter with the option of EnergyType
that is passed into the encode()
function. The below chart will automatically pick colors to pass into the chart for each of the energy types since no specific colors are specified.
Below is the code used to create the chart below:
energy_source = pd.DataFrame({ "EnergyType": ["Electricity","Gasoline","Natural Gas","Electricity","Gasoline","Natural Gas","Electricity","Gasoline","Natural Gas"], "Price ($)": [150,73,15,130,80,20,170,83,20], "Date": ["2022-1-23", "2022-1-30","2022-1-5","2022-2-21", "2022-2-1","2022-2-1","2022-3-1","2022-3-1","2022-3-1"] }) bar_chart = alt.Chart(energy_source).mark_bar().encode( x="month(Date):O", y="sum(Price ($)):Q", color="EnergyType:N" ) st.altair_chart(bar_chart, use_container_width=True)
Streamlit Altair Stacked Bar Chart Change Colors
It’s possible to specifically choose the colors for an Altair chart on Streamlit visuals by changing the colors passed into the encode function.
The color object in the encode function is passed a color called alt.Color()
, which specifies first the category and then passes in two lists the domain and range. The color in the range is mapped to the categories of the domain for each of the energy types.
Below is the code used to create the chart below:
domain = ["Electricity", "Gasoline", "Natural Gas"] range_ = ["red", "green", "blue"] bar_chart = alt.Chart(energy_source).mark_bar().encode( x="month(Date):O", y="sum(Price ($)):Q", color=alt.Color("EnergyType", scale=alt.Scale(domain=domain, range=range_)) ) st.altair_chart(bar_chart, use_container_width=True)
Streamlit Altair Bar Stacked Chart Horizontal
Simply put the quantitive value on the x-axis to make the bar chart horizontal. This is done by specifying putting a number type, which is :Q quantitative in Altair charts on the x-axis.
Here is the code that controls the visual below:
"Energy Costs By Month" bar_chart = alt.Chart(energy_source).mark_bar().encode( y="month(Date):O", x="sum(Price ($)):Q", color="EnergyType:N" ) st.altair_chart(bar_chart, use_container_width=True)
Streamlit Altair Bar Chart Sorted
The sort is controlled by the sort of -x in the alt.Y("Month:N", sort=
“-x”)
In this case, this sort gets passed into the encode function via the y which is what makes the graph sorted in descending order.
Below is the code that controls the visual below:
source = pd.DataFrame({ "Price ($)": [10, 15, 20], "Month": ["January", "February", "March"] }) bar_chart = alt.Chart(source).mark_bar().encode( x="sum(Price ($)):Q", y=alt.Y("Month:N", sort="-x") ) st.altair_chart(bar_chart, use_container_width=True)
Conclusion
In conclusion, you can see all the great bar chart visuals that can be produced by Streamlit.
You saw just how easy it is to create the bar charts visuals and how customizable they are.
As you saw Altair charts are a great choice for creating compelling charts in Streamlit. These bar charts can be a compelling visual component to your ‘data apps’, especially with Streamlit!