04-29-2022, 10:52 PM
Line Charts — Learning Line Charts with Streamlit
Streamlit is an easy-to-use rapid web application development platform. It can create compelling data visualizations using python.
Line charts are one of the many types of charts that Streamlit can display. Line charts are often a great visual for displaying numerical data over time.
This tutorial will teach you how to easily create and configure line charts in Streamlit with the Altair Chart library.
Below is a vivid line chart graph that you can create with Altair Charts:
![[Image: image-236-1024x560.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-236-1024x560.png)
This tutorial will teach you how to make line charts by walking you through the creation and the altering of simple line charts. It will then show you how a more sophisticated multi-line chart like the one above.
The source code for the tutorial is here on Github.
The following imports will need to be made to follow along with the tutorial
Create a Simple Line Chart with Altair
To create a line chart with the most basic configuration simply use the below code.
The first step you need to do is to create or import a data frame.
To create a line chart there must be one or more number types or one ordinal, which is an ordered type like a date.
Below is a simple example data frame called. It’ll be used through the next couple of customizations of the chart with the text you’ll need to import. You can see the energy source data frame was created below. This energy source data frame will be used throughout the tutorial.
The data frame then gets passed to the class that creates the chart object. Now the charts can be extended to different types of graphs.
The function is what creates the chart that reflects the data frame that was passed into the function.
Next, call the function and specify the y-axis and the x-axis. They must be specified for the line chart to be created. Also, the y-axis and the x-axis have to be named as columns in the data frame to work. Finally, the y-axis must be a number and the x-axis must be an ordinal, which is a discrete ordered quantity, on the y-axis like a date.
Here’s the visualization created by the above code:
![[Image: image-237.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-237.png)
[b]Change the Chart Title and Chart Size with Properties[/b]
The chart title and the chart size can be changed by passing in arguments to the properties function.
These get changed with the function by passing in the title. The width and height get passed in to change the overall chart size.
To change the chart title you can chain the function to the end of or a configuration function like in the below example.
You can see the visual of the code created below with the title ‘Energy Bill’:
![[Image: image-238-1024x546.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-238-1024x546.png)
Change the x-Axis and y-Axis Labels
The numerical data the Price ($) is on the y-axis and the non-numerical month (Date) or ordinal (which is a discrete ordered quantity) is on the x-axis.
The default value is the column name. If you want to change the default labels then add the parameter to the function.
In the below example you can see that there is an for the y axis and an for the x-axis parameter that gets a title passed as an option to the function.
The chart titles are changed from ‘Price ($)’ and ‘month(Date)’ to the title of ‘Close Price($)’ and ‘Month’. The axis title size can be changed by configuring the access with that which can be changed to the function and other configuration functions such as properties
Below is what the code looks like to change the axis labels and the visual it creates:
![[Image: image-239-1024x441.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-239-1024x441.png)
Create a Feature-Rich and Complex Chart!
Now that you see the basics of how to create a line chart let’s create a visually-rich chart that adds multiple lines to the chart and creates a custom legend. This chart could be used in a demo or as an end project for a client.
Add Multiple Lines to the Chart and Change Legend Text
Multiple lines on a line chart can be great for the comparison of different categories of data over the same time period and on the same numerical scale.
Multiple lines can be added to the chart by making the data frame have multiple category variables in one column that are then passed into the function.
Below is the chart that gets created:
![[Image: image-240-1024x651.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-240-1024x651.png)
Deploy the Chart to Streamlit.io
Now that you’ve got a seen how to make a line chart. Let’s rapidly deploy it on streamlit.io so it can be shared with others. Streamlit and the Github CLI make the rapid creation of a Streamlit app easy to do.
Streamlit requires a GitHub repository. First, install the Github CLI. Then run the below command.
In the step choose to create from an existing repository and choose the configuration you want.
Now type the rest of the commands that add, commit, and push the code to see what you’ve created.
Finally, add the repository that you’ve created in Streamlit. When you navigate to the app you’ll see the chart you created in a web application.
Go here
![[Image: image-241-1024x285.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-241-1024x285.png)
Then select it and click on deploy.
![[Image: image-242-1024x781.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-242-1024x781.png)
Conclusion
These pieces of demo code should give you a good idea of how to alter the basic functions of the charts.
The last chart is an implementation of the features in the tutorial as well as showing the user how to add multiple lines to a chart and add a chart legend.
The last chart should demonstrate how adding multiple lines to the chart and implementing the above features such as adding a legend, changing the names on the x-axis and the y-axis, and changing the font size. As you can see from this demo adding all these components can create a visually compelling chart!
Streamlit is an easy-to-use rapid web application development platform. It can create compelling data visualizations using python.
Line charts are one of the many types of charts that Streamlit can display. Line charts are often a great visual for displaying numerical data over time.
This tutorial will teach you how to easily create and configure line charts in Streamlit with the Altair Chart library.
Below is a vivid line chart graph that you can create with Altair Charts:
![[Image: image-236-1024x560.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-236-1024x560.png)
This tutorial will teach you how to make line charts by walking you through the creation and the altering of simple line charts. It will then show you how a more sophisticated multi-line chart like the one above.
The source code for the tutorial is here on Github.
The following imports will need to be made to follow along with the tutorial
Code:
pip install streamlit pandas Altair pandas_datareaderTo create a line chart with the most basic configuration simply use the below code.
Code:
import pandas as pd
import Altair as alt
import streamlit as st energy_source = pd.DataFrame({ "EnergyType": ["Electricity", "Gasoline", "Natural Gas", "Electricity", "Gasoline", "Natural Gas", "Electricity", "Gasoline", "Natural Gas"], "Price ($)": [150, 100, 30, 130, 80, 70, 170, 83, 70], "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"]
}) line_chart = alt.Chart(energy_source).mark_line().encode( y= 'Price ($)', x='month(Date)', )The first step you need to do is to create or import a data frame.
To create a line chart there must be one or more number types or one ordinal, which is an ordered type like a date.
Below is a simple example data frame called
Code:
energy_sourceThe data frame then gets passed to the
Code:
alt.Chart()The
Code:
mark_line()Next, call the
Code:
encode()Here’s the visualization created by the above code:
![[Image: image-237.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-237.png)
[b]Change the Chart Title and Chart Size with Properties[/b]
The chart title and the chart size can be changed by passing in arguments to the properties function.
These get changed with the
Code:
properties()To change the chart title you can chain the
Code:
configure_title()Code:
encode()Code:
properties()Code:
line_chart = alt.Chart(energy_source).mark_line().encode( y= alt.Y('Price ($)', title='Close Price($)'), x= alt.X( 'month(Date)', title='Month') ).properties( height=400, width=700, title="Energy Bill" ).configure_title( fontSize=16 ) st.altair_chart(line_chart, use_container_width=True)You can see the visual of the code created below with the title ‘Energy Bill’:
![[Image: image-238-1024x546.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-238-1024x546.png)
Change the x-Axis and y-Axis Labels
The numerical data the Price ($) is on the y-axis and the non-numerical month (Date) or ordinal (which is a discrete ordered quantity) is on the x-axis.
The default value is the column name. If you want to change the default labels then add the
Code:
titleCode:
altIn the below example you can see that there is an
Code:
alt.Y()Code:
alt.X()Code:
encode()The chart titles are changed from ‘Price ($)’ and ‘month(Date)’ to the title of ‘Close Price($)’ and ‘Month’. The axis title size can be changed by configuring the access with that which can be changed to the
Code:
encode()Below is what the code looks like to change the axis labels and the visual it creates:
Code:
line_chart = alt.Chart(energy_source).mark_line().encode( y= alt.Y('Price ($)', title='Close Price($)'), x= alt.X( 'month(Date)', title='Month') ).configure_axis( titleFontSize=14, labelFontSize=12 ) st.altair_chart(line_chart, use_container_width=True)![[Image: image-239-1024x441.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-239-1024x441.png)
Create a Feature-Rich and Complex Chart!
Now that you see the basics of how to create a line chart let’s create a visually-rich chart that adds multiple lines to the chart and creates a custom legend. This chart could be used in a demo or as an end project for a client.
Add Multiple Lines to the Chart and Change Legend Text
Multiple lines on a line chart can be great for the comparison of different categories of data over the same time period and on the same numerical scale.
Multiple lines can be added to the chart by making the data frame have multiple category variables in one column that are then passed into the
Code:
color()- The first step is to get a data frame. This is done in the below code by getting . This gets one data frame from aCode:
get_stock_dfclass that contains stock information. The stock symbol determines what stock information the data source gets from yahoo and the start and the end date are what get the data back from.Code:data.DataReader
Code:
def get_stock_df(symbol,start,end): source = 'yahoo' df = data.DataReader( symbol, start=start, end=end, data_source=source ) return df- The second is . TheCode:
get_stock_combined()combined combines all the stocks into one data frame. In this different stock symbols of ULT, LIT, USO, and UNG are categories of the below stocks. These different stock categories in theCode:get_stockpassed in the line chart are what are used to create multiple lines in the line chart. The name of the stocks being passed in the color function is what is used to create a legend.Code:symbol['SymbolFullName']
- The final step is to create the line chart. The line chart is created by using all the steps above. The line variable being passed into streamlit is what creates the chart.
Code:
import streamlit as st
import pandas as pd
import altair as alt
from pandas_datareader import data def get_stock_df(symbol,start,end): source = 'yahoo' df = data.DataReader( symbol, start=start, end=end, data_source=source ) return df def get_stock_combined(symbols,start,end): dfs = [] for symbol in symbols.keys(): df = get_stock_df(symbol,start,end) df['Symbol'] = symbol df['SymbolFullName'] = symbols[symbol] dfs.append(df) df_combined = pd.concat(dfs, axis=0) df_combined['date'] = df_combined.index.values return df_combined def get_stock_title(stocks): title = "" idx = 0 for i in stocks.keys(): title = title + stocks[i] if idx < len(stocks.keys()) - 1: title = title + " & " idx = idx + 1 return title stocks = {"LIT":"Lithium","USO":"United States Oil ETF","UNG":"Natural Gas Fund","USL":"US 12 Month Natural Gas Fund (UNL)"} stock_title = get_stock_title(stocks) start = '2021-06-01' end = '2022-08-01' df_combined = get_stock_combined(stocks,start,end) line = alt.Chart(df_combined).mark_line().encode( alt.X("date", title="Date"), alt.Y("Close", title="Closing Price", scale=alt.Scale(zero=False)), color='SymbolFullName' ).properties( height=400, width=650, title=stock_title ).configure_title( fontSize=16 ).configure_axis( titleFontSize=14, labelFontSize=12 ) lineBelow is the chart that gets created:
![[Image: image-240-1024x651.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-240-1024x651.png)
Deploy the Chart to Streamlit.io
Now that you’ve got a seen how to make a line chart. Let’s rapidly deploy it on streamlit.io so it can be shared with others. Streamlit and the Github CLI make the rapid creation of a Streamlit app easy to do.
Streamlit requires a GitHub repository. First, install the Github CLI. Then run the below command.
Code:
gh repo createIn the
Code:
gh repo createCode:
git repoNow type the rest of the commands that add, commit, and push the code to see what you’ve created.
Code:
git add .
git commit -m "add file"
git pushFinally, add the repository that you’ve created in Streamlit. When you navigate to the app you’ll see the chart you created in a web application.
Go here
![[Image: image-241-1024x285.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-241-1024x285.png)
Then select it and click on deploy.
![[Image: image-242-1024x781.png]](https://blog.finxter.com/wp-content/uploads/2022/04/image-242-1024x781.png)
Conclusion
These pieces of demo code should give you a good idea of how to alter the basic functions of the charts.
The last chart is an implementation of the features in the tutorial as well as showing the user how to add multiple lines to a chart and add a chart legend.
The last chart should demonstrate how adding multiple lines to the chart and implementing the above features such as adding a legend, changing the names on the x-axis and the y-axis, and changing the font size. As you can see from this demo adding all these components can create a visually compelling chart!

