Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Line Charts — Learning Line Charts with Streamlit

#1
Line Charts — Learning Line Charts with Streamlit

<div><figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Line Charts -- Learning Line Charts with Streamlit" width="780" height="439" src="https://www.youtube.com/embed/b6ZIQ67uIdc?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<p>Streamlit is an easy-to-use rapid web application development platform. It can create compelling data visualizations using python.</p>
<p>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.&nbsp; </p>
<p><strong>This tutorial will teach you how to easily create and configure line charts in Streamlit with the Altair Chart library.&nbsp;</strong></p>
<p>Below is a vivid line chart graph that you can create with Altair Charts:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="560" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-236-1024x560.png" alt="" class="wp-image-324936" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-236-1024x560.png 1024w, https://blog.finxter.com/wp-content/uplo...00x164.png 300w, https://blog.finxter.com/wp-content/uplo...68x420.png 768w, https://blog.finxter.com/wp-content/uplo...ge-236.png 1330w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p>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. </p>
<p>The source code for the tutorial is here on <a href="https://github.com/ggrow3/Streamlit_Line_Chart">Github</a>. </p>
<p>The following imports will need to be made to follow along with the tutorial&nbsp;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">pip install streamlit pandas Altair pandas_datareader</pre>
<h2>Create a Simple Line Chart with Altair</h2>
<p>To create a line chart with the most basic configuration simply use the below code.&nbsp;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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)', )
</pre>
<p>The first step you need to do is to create or import a <a href="https://blog.finxter.com/how-to-create-a-dataframe-in-pandas/" target="_blank" rel="noreferrer noopener">data frame</a>. </p>
<p>To create a line chart there must be one or more number types or one ordinal, which is an ordered type like a date. </p>
<p>Below is a simple example data frame called <code>energy_source</code>. 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.</p>
<p>The data frame then gets passed to the <code>alt.Chart()</code> class that creates the chart object. Now the charts can be extended to different types of graphs.&nbsp;</p>
<p>The <code>mark_line()</code> function is what creates the chart that reflects the data frame that was passed into the function.</p>
<p>Next, call the <code>encode()</code> 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.&nbsp;</p>
<p>Here’s the visualization created by the above code:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" width="974" height="404" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-237.png" alt="" class="wp-image-324937" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-237.png 974w, https://blog.finxter.com/wp-content/uplo...00x124.png 300w, https://blog.finxter.com/wp-content/uplo...68x319.png 768w" sizes="(max-width: 974px) 100vw, 974px" /></figure>
</div>
<h2><strong>Change the Chart Title and Chart Size with Properties</strong></h2>
<p>The chart title and the chart size can be changed by passing in arguments to the properties function. </p>
<p>These get changed with the <code>properties()</code> function by passing in the title. The width and height get passed in to change the overall chart size.&nbsp; </p>
<p>To change the chart title you can chain the <code>configure_title()</code> function to the end of <code>encode()</code> or a configuration function like <code>properties()</code> in the below example.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> 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)</pre>
<p>You can see the visual of the code created below with the title <em>‘Energy Bill’</em>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="546" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-238-1024x546.png" alt="" class="wp-image-324938" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-238-1024x546.png 1024w, https://blog.finxter.com/wp-content/uplo...00x160.png 300w, https://blog.finxter.com/wp-content/uplo...68x409.png 768w, https://blog.finxter.com/wp-content/uplo...ge-238.png 1233w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Change the x-Axis and y-Axis Labels</h2>
<p>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. </p>
<p>The default value is the column name. If you want to change the default labels then add the <code>title</code> parameter to the <code>alt</code> function. </p>
<p>In the below example you can see that there is an <code>alt.Y()</code> for the y axis and an <code>alt.X()</code> for the x-axis parameter that gets a title passed as an option to the <code>encode()</code> function.&nbsp; </p>
<p>The chart titles are changed from <strong><em>‘Price ($)’</em></strong> and <strong><em>‘month(Date)’</em></strong> to the title of <strong><em>‘Close Price($)’</em></strong> and <strong><em>‘Month’</em></strong>. The axis title size can be changed by configuring the access with that which can be changed to the <code>encode()</code> function and other configuration functions such as properties&nbsp;</p>
<p>Below is what the code looks like to change the axis labels and the visual it creates:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""> 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)</pre>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="441" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-239-1024x441.png" alt="" class="wp-image-324939" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-239-1024x441.png 1024w, https://blog.finxter.com/wp-content/uplo...00x129.png 300w, https://blog.finxter.com/wp-content/uplo...68x331.png 768w, https://blog.finxter.com/wp-content/uplo...ge-239.png 1244w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Create a Feature-Rich and Complex Chart!</h2>
<p>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.&nbsp;</p>
<h2>Add Multiple Lines to the Chart and Change Legend Text</h2>
<p>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.</p>
<p>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()</code> function.&nbsp;</p>
<ol>
<li>The first step is to get a data frame. This is done in the below code by getting <code>get_stock_df</code>. This gets one data frame from a <code>data.DataReader</code> 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.</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def get_stock_df(symbol,start,end): source = 'yahoo' df = data.DataReader( symbol, start=start, end=end, data_source=source ) return df</pre>
<ol start="2">
<li>The second is <code>get_stock_combined()</code>. The <code>get_stock</code> 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 <code>symbol['SymbolFullName']</code> 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.&nbsp;&nbsp;</li>
<li>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.&nbsp;</li>
</ol>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">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 &lt; len(stocks.keys()) - 1: title = title + " &amp; " 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
</pre>
<p>Below is the chart that gets created:</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="651" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-240-1024x651.png" alt="" class="wp-image-324940" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-240-1024x651.png 1024w, https://blog.finxter.com/wp-content/uplo...00x191.png 300w, https://blog.finxter.com/wp-content/uplo...68x488.png 768w, https://blog.finxter.com/wp-content/uplo...36x977.png 1536w, https://blog.finxter.com/wp-content/uplo...ge-240.png 1596w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Deploy the Chart to Streamlit.io&nbsp;&nbsp;&nbsp;</h2>
<p>Now that you’ve got a seen how to make a line chart. Let’s rapidly deploy it on <a rel="noreferrer noopener" href="https://streamlit.io/" target="_blank">streamlit.io</a> so it can be shared with others. Streamlit and the <a rel="noreferrer noopener" href="https://cli.github.com/" target="_blank">Github CLI</a> make the rapid creation of a Streamlit app easy to do. </p>
<p>Streamlit requires a GitHub repository. First, install the <a rel="noreferrer noopener" href="https://cli.github.com/" target="_blank">Github CLI</a>. Then run the below command.&nbsp;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">gh repo create</pre>
<p>In the <code>gh repo create</code> step choose <code>git repo</code> to create from an existing repository and choose the configuration you want.</p>
<p>Now type the rest of the commands that add, commit, and push the code to see what you’ve created.&nbsp;&nbsp;</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">git add .
git commit -m "add file"
git push</pre>
<p>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.&nbsp;</p>
<p>Go here&nbsp;</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="285" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-241-1024x285.png" alt="" class="wp-image-324941" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-241-1024x285.png 1024w, https://blog.finxter.com/wp-content/uplo...300x83.png 300w, https://blog.finxter.com/wp-content/uplo...68x214.png 768w, https://blog.finxter.com/wp-content/uplo...36x427.png 1536w, https://blog.finxter.com/wp-content/uplo...ge-241.png 1600w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<p>Then select it and click on deploy.&nbsp;</p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img loading="lazy" width="1024" height="781" src="https://blog.finxter.com/wp-content/uploads/2022/04/image-242-1024x781.png" alt="" class="wp-image-324942" srcset="https://blog.finxter.com/wp-content/uploads/2022/04/image-242-1024x781.png 1024w, https://blog.finxter.com/wp-content/uplo...00x229.png 300w, https://blog.finxter.com/wp-content/uplo...68x586.png 768w, https://blog.finxter.com/wp-content/uplo...ge-242.png 1498w" sizes="(max-width: 1024px) 100vw, 1024px" /></figure>
</div>
<h2>Conclusion</h2>
<p>These pieces of demo code should give you a good idea of how to alter the basic functions of the charts.&nbsp; </p>
<p>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.&nbsp; </p>
<p>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!</p>
<hr class="wp-block-separator"/>
</div>


https://www.sickgaming.net/blog/2022/04/...streamlit/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016