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:

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 

pip install streamlit pandas Altair pandas_datareader

Create a Simple Line Chart with Altair

To create a line chart with the most basic configuration simply use the below 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 energy_source. 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 alt.Chart() class that creates the chart object. Now the charts can be extended to different types of graphs. 

The mark_line() function is what creates the chart that reflects the data frame that was passed into the function.

Next, call the encode() 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:

Change the Chart Title and Chart Size with Properties

The chart title and the chart size can be changed by passing in arguments to the properties function.

These get changed with the properties() 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 configure_title() function to the end of encode() or a configuration function like properties() in the below example.

  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’:

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 title parameter to the alt function.

In the below example you can see that there is an alt.Y() for the y axis and an alt.X() for the x-axis parameter that gets a title passed as an option to the encode() 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 encode() 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:

  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)

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 color() function. 

  1. The first step is to get a data frame. This is done in the below code by getting get_stock_df. This gets one data frame from a data.DataReader class 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.
def get_stock_df(symbol,start,end):
   source = 'yahoo'
   df = data.DataReader(
      symbol, start=start, end=end, data_source=source
   )
   return df
  1. The second is get_stock_combined(). The get_stock 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 the symbol['SymbolFullName'] passed 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.  
  2. 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. 
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
    )
    line

Below is the chart that gets created:

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. 

gh repo create

In the gh repo create step choose git repo 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.  

git add .
git commit -m "add file"
git push

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 

Then select it and click on deploy. 

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!