Reader small image

You're reading from  Streamlit for Data Science - Second Edition

Product typeBook
Published inSep 2023
Reading LevelBeginner
PublisherPackt
ISBN-139781803248226
Edition2nd Edition
Languages
Concepts
Right arrow
Author (1)
Tyler Richards
Tyler Richards
author image
Tyler Richards

Tyler Richards is a senior data scientist at Snowflake, working on a variety of Streamlit-related projects. Before this, he worked on integrity as a data scientist for Meta and non-profits like Protect Democracy. While at Facebook, he launched the first version of this book and subsequently started working at Streamlit, which was acquired by Snowflake early in 2022.
Read more about Tyler Richards

Right arrow

Streamlit plotting demo

First, we're going to start to learn how to make Streamlit apps by reproducing the plotting demo we saw before in the Streamlit demo, with a Python file that we've made ourselves. In order to do that, we will do the following:

  1. Make a Python file where we will house all our Streamlit code.
  2. Use the plotting code given in the demo.
  3. Make small edits for practice.
  4. Run our file locally.

Our first step is to create a folder called plotting_app, which will house our first example. The following code makes this folder when run in the terminal, changes our working directory to plotting_app, and creates an empty Python file we'll call plot_demo.py:

mkdir plotting_app
cd plotting_app
touch plot_demo.py

Now that we've made a file called plot_demo.py, open it with any text editor (if you don't have one already, I'm partial to VS Code (https://code.visualstudio.com/download). When you open it up, copy and paste the...

Making an app from scratch

Now that we've tried out the apps others have made, let's make our own! This app is going to focus on using the central limit theorem, which is a fundamental theorem of statistics that says that if we randomly sample with replacement enough from any distribution, then the distribution of the mean of our samples will approximate the normal distribution.

We are not going to prove this with our app, but instead, let's try to generate a few graphs that help explain the power of the central limit theorem. First, let's make sure that we're in the correct directory (in this case, the streamlit_apps folder that we created earlier), make a new folder called clt_app, and toss in a new file.

The following code makes a new folder called clt_app, and again creates an empty Python file, this time called clt_demo.py:

mkdir clt_app
cd clt_app
touch clt_demo.py

Whenever we start a new Streamlit app, we want to make sure to...

Summary

In this chapter, we started by learning how to organize our files and folders for the remainder of this book and quickly moved on to instructions for downloading Streamlit. We then built our first Streamlit application, Hello World, and learned how to run our Streamlit applications locally. Then we started building out a more complicated application to show the implications of the central limit theorem from the ground up, going from a simple histogram to accepting user input and formatting different types of text around our app for clarity and beautification.

By now, you should be comfortable with subjects such as basic data visualization, editing Streamlit apps in a text editor, and locally running Streamlit apps. We're going to dive more deeply into data manipulation in our next chapter.

Exploring Palmer’s Penguins

Before we begin working with this dataset, we should make some visualizations to better understand the data. As we saw before, we have many columns in this data, whether the bill length, the flipper length, the island the penguin lives on, or even the species of penguin. I’ve done the first visualization for us already in Altair, a popular visualization library that we will use extensively throughout this book because it is interactive by default and generally pretty:

Figure 2.2: Bill length and bill depth

From this, we can see that the Adelie penguins have a shorter bill length but generally have fairly deep bills. Now, what does it look like if we plot weight by flipper length?

Figure 2.3: Bill length and weight

Now we see that Gentoo penguins seem to be heavier than the other two species, and that bill length and body mass are positively correlated. These findings are not a huge surprise, but getting to these simple...

Flow control in Streamlit

As we talked about just before, there are two solutions to this data upload default situation. We can provide a default file to use until the user interacts with the application, or we can stop the app until a file is uploaded. Let’s start with the first option. The following code uses the st.file_uploader() function from within an if statement. If the user uploads a file, then the app uses that; if they do not, then we default to the file we have used before:

import altair as alt
import pandas as pd
import seaborn as sns
import streamlit as st
 
st.title("Palmer's Penguins")
st.markdown("Use this Streamlit app to make your own scatterplot about penguins!")
 
penguin_file = st.file_uploader("Select Your Local Penguins CSV (default provided)")
if penguin_file is not None:
    penguins_df = pd.read_csv(penguin_file)
else:
    penguins_df = pd.read_csv("penguins.csv")
 
selected_x_var = st.selectbox(
 ...

Debugging Streamlit apps

We broadly have two options for Streamlit development:

  • Develop in Streamlit and st.write() as a debugger.
  • Explore in Jupyter and then copy to Streamlit.

Developing in Streamlit

In the first option, we write our code directly in Streamlit as we’re experimenting and exploring exactly what our application will do. We’ve basically been taking this option already, which works very well if we have less exploration work and more implementation work to do.

Pros:

  • What you see is what you get – there is no need to maintain both IPython and Python versions of the same app.
  • Better experience for learning how to write production code.

Cons:

  • A slower feedback loop (the entire app must run before feedback).
  • A potentially unfamiliar development environment.

Exploring in Jupyter and then copying to Streamlit

Another option is to utilize the extremely popular Jupyter data science product to write and test out the Streamlit app’s code before placing it in the necessary script and formatting it correctly. This can be useful for exploring new functions that will live in the Streamlit app, but it has serious downsides.

Pros:

  • The lightning-fast feedback loop makes it easier to experiment with very large apps.
  • Users may be more familiar with Jupyter.
  • The full app does not have to be run to get results, as Jupyter can be run in individual cells.

Cons:

  • Jupyter may provide deceptive results if run out of order.
  • “Copying” code over from Jupyter is time-consuming.
  • Python versioning may be different between Jupyter and Streamlit.

My recommendation here is to develop Streamlit apps inside the environment where they are going to be run (that is, a Python file)....

Data manipulation in Streamlit

Streamlit runs our Python file from the top down as a script, so we can perform data manipulation with powerful libraries such as pandas in the same way that we might in a Jupyter notebook or a regular Python script. As we’ve discussed before, we can do all our regular data manipulation as normal. For our Palmer’s Penguins app, what if we wanted the user to be able to filter out penguins based on their gender? The following code filters our DataFrame using pandas:

import streamlit as st
import pandas as pd
import altair as alt 
import seaborn as sns
st.title("Palmer's Penguins")
st.markdown('Use this Streamlit app to make your own scatterplot about penguins!')
penguin_file = st.file_uploader(
    'Select Your Local Penguins CSV (default provided)')
if penguin_file is not None:
    penguins_df = pd.read_csv(penguin_file)
else:
    penguins_df = pd.read_csv('penguins.csv')
selected_x_var =...

An introduction to caching

As we create more computationally intensive Streamlit apps and begin to use and upload larger datasets, we should start thinking about the runtime of these apps and work to increase our efficiency whenever possible. The easiest way to make a Streamlit app more efficient is through caching, which is storing some results in memory so that the app does not repeat the same work whenever possible.

A good analogy for an app’s cache is a human’s short-term memory, where we keep bits of information close at hand that we think might be useful. When something is in our short-term memory, we don’t have to think very hard to get access to that piece of information. In the same way, when we cache a piece of information in Streamlit, we are making a bet that we’ll use that information often.

The way Streamlit caching works more specifically is by storing the results of a function in our app, and if that function is called with the same...

Persistence with Session State

One of the most frustrating parts of the Streamlit operating model for developers starting out is the combination of two facts:

  1. By default, information is not stored across reruns of the app.
  2. On user input, Streamlits are rerun top-to-bottom.

These two facts make it difficult to make certain types of apps! This is best shown in an example. Let’s say that we want to make a to-do app that makes it easy for you to add items to your to-do list. Adding user input in Streamlit is really simple, so we can create one quickly in a new file called session_state_example.py that looks like the following:

import streamlit as st
st.title('My To-Do List Creator')
my_todo_list = ["Buy groceries", "Learn Streamlit", "Learn Python"]
st.write('My current To-Do list is:', my_todo_list)
new_todo = st.text_input("What do you need to do?")
if st.button('Add the new To-Do...

Summary

This chapter was full of fundamental building blocks that we will use often throughout the remainder of this book, and that you will use to develop your own Streamlit applications.

In terms of data, we covered how to bring our own DataFrames into Streamlit and how to accept user input in the form of a data file, which brings us past only being able to simulate data. In terms of other skill sets, we learned how to use our cache to make our data apps faster, how to control the flow of our Streamlit apps, and how to debug our Streamlit apps using st.write(). That’s it for this chapter. Next, we’ll move on to data visualization!

Learn more on Discord

To join the Discord community for this book – where you can share feedback, ask questions to the author, and learn about new releases – follow the QR code below:

https://packt.link/sl

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Streamlit for Data Science - Second Edition
Published in: Sep 2023Publisher: PacktISBN-13: 9781803248226
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Tyler Richards

Tyler Richards is a senior data scientist at Snowflake, working on a variety of Streamlit-related projects. Before this, he worked on integrity as a data scientist for Meta and non-profits like Protect Democracy. While at Facebook, he launched the first version of this book and subsequently started working at Streamlit, which was acquired by Snowflake early in 2022.
Read more about Tyler Richards