100% found this document useful (2 votes)
153 views62 pages

16 - Streamlit

Uploaded by

dataanalystej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
153 views62 pages

16 - Streamlit

Uploaded by

dataanalystej
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 62

Web Applications

Introduction to Streamlit
Web Applications
➢Streamlit
➢Text elements
➢Input widgets
➢Data visualization
➢Additional elements
➢Layout

1
Streamlit
Web Applications

2
Python Libraries
• Python offers several libraries for analyzing, manipulating data, and
developing interfaces to facilitate the creation of data analysis
applications

Library used to work with datasets. Library (Numeric Python) that allows you
Analyze, clean, explore, and to work with numerical data, with
manipulate data multidimensional data structures (i.e.,
array, matrix)

Open-source library that


facilitates the creation and
development of custom web
applications
3
NumPy
• The main advantages of NumPy are to increase flexibility and
efficiency of operations compared to the native structures of Python
➢ import numpy as np
• The data structure revolves around the concept of array, a grid of
values referred to as ndarray (N-dimensional array)
• Dimensions are called axes
• Numpy is the basis of other advanced Python libraries (e.g., Pandas,
Scikit-learn)

https://numpy.org/doc/stable/index.html
4
NumPy - Examples

Creation of a matrix Indexing and slicing

Reshape an array Aggregations on different axes

https://numpy.org/doc/stable/index.html
5
Pandas
• A fundamental library especially in the field of Data Science together with NumPy
(on which it is based)
➢ import numpy as np
➢ import pandas as pd
• There are two fundamental data structures: Series (1-D sequence of
homogeneous elements) and DataFrame (2-D arrays designed as tables, each
column is a Series and has a name)
• Example: browse, analyze, and visualize data from a CSV file

https://pandas.pydata.org/docs/index.html
6
Pandas
• Data Loading: a DataFrame can be created from Series, numpy arrays,
dictionaries, JSON, CSV…
• Data Cleaning: different functions for data cleaning, removing duplicate data,
replacing missing values with default values, converting data types…
• Data Manipulation: filtering rows, sorting data, creating new columns,
aggregating data…
• Data Analysis: view descriptive statistics, create PivotTables, create charts, and
other advanced analysis…
• Data Visualization: visualization of data with different types of graphs, using the
Matplotlib library

7
Pandas - Examples
import pandas as pd

# Creating a Dataframe from a Dictionary


data = {'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Mauro'],
'Age': [25, 33, 47, 19, 28, 17],
'City': ['Rome', 'Milan', 'Naples', 'Turin'', 'Florence', 'Turin'']}
df = pd.DataFrame(data)

# Print the first 5 rows of the dataframe


print(df.head())

# Print column list


print(df.columns)

# Filter rows with age greater than 30 years


df_filtered = df[df['Age'] > 30]
print(df_filtered)

# Aggregate data by city and calculate the average age


df_aggregate = df.groupby('City')['Age'].mean()
print(df_aggregate)

# Create a new column that indicates whether the person is


of legal age or underage
df['Adult'] = df['Age'].apply(lambda x: 'Yes' if x >= 18
else 'No')

# Delete the Age column


df_output=df.drop(columns=['Age'])
print(df_output)

# Save dataframe to a CSV file


people.csv
df_output.to_csv('people.csv', index=False)

8
Why Streamlit?
• Open-source Python library that facilitates the creation and
development of custom web applications
• Ideal for supporting data science and machine learning projects
• You can create interactive interfaces
• Designed for newbies, front-end skills are not expressly required
• Thanks to widgets and elements available, you can create web pages
with a few lines of code
• Compatible with most Python libraries

https://streamlit.io/
9
Examples gallery
• There are several templates and applications created by the community
(https://streamlit.io/gallery)

Background Removal Bundesliga analyzer

SWAST - Hospital Handover Report 10


Installation
• Python 3.7 – Python 3.11
• Using a virtual environment is always recommended (pipenv, poetry, venv...)
• Install Streamlit
➢ pip install streamlit

• Test the installation


➢ streamlit hello

• Launch your own application


➢ streamlit run your_script.py [-- script args]
Or
➢ python -m streamlit run your_script.py

https://docs.streamlit.io/library/get-started/installation
11
Configuration
• Various possibilities to define configuration options (e.g., server port,
theme...) via:
1. a global config file (to be created):
➢ ~/.streamlit/config.toml for macOS/Linux
➢ %userprofile%/.streamlit/config.toml for Windows

2. a per-project configuration file:


➢ $CWD/.streamlit/config.toml where $CWD is the folder from which Streamlit was launched

3. a command line flag:


➢ streamlit run your_script.py --server.port 80

https://docs.streamlit.io/library/advanced-features/configuration
12
Telemetry
• Statistical information on the use by users is collected
• To disable telemetry, you must specify the configuration option

The server must be restarted to update configuration options

https://docs.streamlit.io/library/advanced-features/configuration
13
Start
Command to
start Streamlit

Hamburger
menu

URL to reach the web


server at port 8501

Sidebar with access to


sample demos
14
Development
• Every time the Python script is saved, the application updates with a
click on Rerun, without the need to restart the server
• By choosing Always rerun, the application updates automatically with
each save, allowing you to immediately see the changes
• Whenever something needs to be updated on the screen (including
user interactions), Streamlit launches the top-to-bottom script
entirely.
• The server can be stopped with
Ctrl+C

15
Project structure
• Before you develop your app, it's important to define the project
directory structure
• You need to define an entrypoint file that represents the main page
to show to the user
• Other additional pages should be placed in a sub-folder pages
• Pages globally share the same Python modules

16
Application pages
• Pages are defined by files .py within the "pages/" folder
• File names are transformed into page names
• The order is given by the number preceding the title and/or by the
alphabetical order of the title itself.
• The number used as a prefix in the file name is not interpreted as part
of the title

17
Page configuration
• Set the default page configuration
➢ st.set_page_config(page_title=None, page_icon=None, layout="centered",
initial_sidebar_state="auto", menu_items=None)

It must be the first Streamlit command and set only once!

18
Customization of the hamburger menu
• Using the menu_items parameter, you can customize the items to be
shown in the hamburger menu
• It must be formatted according to a dictionary in which the key is the
element you want to change

19
Elements of Streamlit
• Widgets and elements specific to different types of activities and inputs
• quickly integrate different features into your application
• available through official documentation:
https://docs.streamlit.io/library/api-reference
• Most significant categories:
• Text elements
• Input widgets
• Layout
• Visualization of data and graphs
• Additional elements

20
Element arguments
• The various elements can be integrated without special configurations
• Personalization via certain arguments
• Some arguments are common to all (or most) of the elements:
• label: describes to the user the functionality of the element (e.g. the name of
a clickable button)
• label_visibility: determine label visibility (i.e., ”visible”, ”hidden”, ”collapsed”);
the label should always be defined
• disabled: boolean flag to disable an element. Useful for making a widget
available only if a certain condition occurs
• use_container_width: boolean flag to fit the size of the widget to that of the
container it is part of
• key: string or number to uniquely identify the widget. If omitted, it is
generated based on content
Different items cannot have the same key!

21
Text elements
Web Applications
Text elements
• Different ready-to-use text elements, with the ability to customize the
color and insert emojis:
• Title
• Header
• Sub-header
• Text

23
Markdown
• It is possible to insert strings formatted according to the markdown
language
• Markdown is used to format text quickly and easily, being more
readable than other markup languages
• The most common syntax (N.B. spaces are sometimes necessary!):
# Header 1 **bold**
## Header 2 > blockquote
### Header 3 * Item 1
* Item 2
_italics_ Line␣␣
Break

https://www.markdownguide.org/basic-syntax/
24
Markdown example

25
Markdown and HTML
• You can also use markdown to insert HTML code
• Useful for special customizations
• It is necessary to enable the use of HTML code
• the feature is disabled by default to prevent the developer from inserting
unsafe code

26
Write
• Allows to write in the app the arguments that are passed to it
➢ st.write(*args, unsafe_allow_html=False, **kwargs)
• Universal and flexible widget that behaves differently based on the
passed argument
• accepts different types of arguments and renders them accordingly
• multiple arguments can be passed and will be represented
• allows to represent different Python objects (e.g., figure, dataframe,
dictionaries, errors, functions and modules) also in interactive mode

27
Input Widgets
Web Applications
Button
• Allows you to show a simple button that can be clicked by the user
➢ st.button(label, key=None, help=None, on_click=None, args=None, kwargs=None,
type="secondary", disabled=False, use_container_width=False)

29
Checkbox
• Allows you to show a checkbox to check and perform a follow-up
action
➢ st.checkbox(label, value=False, key=None, help=None, on_change=None, args=None,
kwargs=None, *, disabled=False, label_visibility="visible")
• Returns True or False based on checkbox status

30
Radio Button
• Allows you to insert a radio button with which the user can make an
exclusive choice among the proposed alternatives
➢ st.radio(label, options, index=0, format_func=special_internal_function, key=None,
help=None, on_change=None, args=None, kwargs=None, *, disabled=False, horizontal=False,
label_visibility="visible")
• Returns the chosen option

31
Select Box
• Allows you to insert a drop-down selection box with which the user
can choose between the various alternatives
➢ st.selectbox(label, options, index=0, format_func=special_internal_function, key=None,
help=None, on_change=None, args=None, kwargs=None, *, disabled=False,
label_visibility="visible")
• Returns the chosen option

32
Multiselect
• Allows the user to choose multiple alternatives among those proposed
➢ st.multiselect(label, options, default=None, format_func=special_internal_function, key=None,
help=None, on_change=None, args=None, kwargs=None, *, disabled=False,
label_visibility="visible", max_selections=None)
• The default parameter specifies the list of options selected at startup
• The max_selections parameter defines the maximum number of options
that can be selected
• Returns the list of selected options

33
Slider
• Offers a slider that accepts: int, float, time, date and datetime
➢ st.slider(label, min_value=None, max_value=None, value=None, step=None, format=None,
key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False,
label_visibility="visible")
• Allows you to select both a single value and a range of values
• Returns the selected value or tuple (for ranges)
• The min_value (default 0 if int, 0.0 if float) and max_value (default
100 if int, 1.0 if float) parameters define the minimum and maximum
allowed value, respectively.

34
Slider
• Offers a slider that accepts: int, float, time, date and datetime
➢ st.slider(label, min_value=None, max_value=None, value=None, step=None, format=None,
key=None, help=None, on_change=None, args=None, kwargs=None, *, disabled=False,
label_visibility="visible")
• The value parameter defines the assumed value when the slider is
loaded for the first time
• If set with a tuple, create a slider with the selectable range
• by default it is set to min_value
• The step parameter defines the interval between one value and
another (default 1 if int, 0.01 if float)

35
Slider Example

36
Text and Number
• Text input offers the possibility of single-line text input
➢ st.text_input(label, value="", max_chars=None, key=None, type="default", help=None,
autocomplete=None, on_change=None, args=None, kwargs=None, *, placeholder=None,
disabled=False, label_visibility="visible")

• The number input allows you to pass a number that can be written from the
keyboard or using the ‘+’ and ‘-’ keys
➢ st.number_input(label, min_value=None, max_value=None, value=, step=None,
format=None, key=None, help=None, on_change=None, args=None, kwargs=None, *,
disabled=False, label_visibility="visible")

37
Date input
• Provides an ideal widget for selecting a date on a calendar
➢ st.date_input(label, value=None, min_value=None, max_value=None, key=None,
help=None, on_change=None, args=None, kwargs=None, *, disabled=False,
label_visibility="visible")
• The value parameter also accepts a list/tuple to enable a date range

38
Form
• Allows you to group several elements on a form (container)
➢ st.form(key, clear_on_submit=False)
• It has integrated a Submit button that collects all the values acquired by the
different widgets
• This parameter clear_on_submit if True resets widget values after user clicks the
Submit button

39
Data visualization
Web Applications
Metrics
• Displays a metric with a specific font, giving you the option to add a
variation indicator
➢ st.metric(label, value, delta=None, delta_color="normal", help=None,
label_visibility="visible")

• The delta parameter indicates the variation

41
Dataframe
• Displays pandas dataframes in the form of interactive tables
➢ st.dataframe(data=None, width=None, height=None, *, use_container_width=False)

42
Charts
• Several libraries are supported for the graphical representation of
data through interactive charts
➢ Matplotlib
➢ Plotly
➢ Altair
➢ deck.gl (maps and 3D graphs)
• To speed up the integration of the most common charts, some are
natively integrated into Streamlit (with less customization):
➢ Line chart
➢ Area chart
➢ Bar chart
➢ Scatterplot on map

43
Line Chart
• It allows you to represent a line chart and is based on Altair
➢ st.line_chart(data=None, *, x=None, y=None, width=0, height=0, use_container_width=True)
• Ideal for simple plots to include quickly and easily
• x and y specify the name of the columns to use on the axes
• Width and height parameters specify dimensions in pixels

44
Bar Chart
• It allows you to represent a bar chart and is based on Altair
➢ st.bar_chart(data=None, *, x=None, y=None, width=0, height=0, use_container_width=True)
• Ideal for simple plots to include quickly and easily
• x and y specify the name of the columns to use on the axes
• Width and height parameters specify dimensions in pixels

45
Map
• Allows you to visualize points on map and it is based on Pydeck
➢ st.map(data=None, zoom=None, use_container_width=True)
• The data parameter must have two columns:
1. Latitude called 'lat', 'latitude', 'LAT', 'LATITUDE'
2. Longitude called 'lon', 'longitude', 'LON', 'LONGITUDE'
• The map relies on the external service Mapbox and requires a token
(currently offered automatically by Streamlit)

46
Additional elements
Web Applications
Additional elements
• Session state
• Elements to customize the application
• For example:
• status messages
• progress bar
• spinner

48
Session state
• A way to share variables between runs and pages, similar to a Python
dictionary
➢ st.session_state
• You must initialize the variable before trying to access it or an
exception is raised
• Each widget with a key is automatically added to the Session State

49
Status messages
• Status messages are useful for rendering warnings, errors, or success
messages
➢ st.error(body, *, icon=None)
➢ st.warning(body, *, icon=None)
➢ st.info(body, *, icon=None)
➢ st.success(body, *, icon=None)

50
Progress bar
• To visualize the progress you can use a progress bar
➢ st.progress(value, text=None)
• The value parameter is 0 to 100 for integers, 0.0 to 1.0 for float
• The text parameter is the text to be shown above the progress bar

51
Spinner
• To show temporary text while a block of code is executed, you can use
a spinner to show to the user
➢ st.spinner(text="In progress...")
• The text parameter is the message to be shown with the spinner until
execution finishes

52
Layout
Web Applications
Sidebar
• The sidebar is very useful for adding elements on the left, leaving the user full
concentration on the main application
• Accept both object notation and with notation
• Layout elements can typically be used as streamlit objects and therefore contain
several elements

54
Columns
• To divide space into side-by-side containers, you can divide the page
into columns
➢ st.columns(spec, *, gap="small")
• The spec parameter can be an integer or a list of numbers
• if an integer, indicates the number of columns to be inserted, all with the
same width
• If a list, a column is created for each number with width proportional to the
specified number
• The gap parameter indicates the distance between the columns
• The list of containers (i.e., columns) is returned
• Accept both object notation and with notation

55
Columns: with notation example

56
Columns: object notation example

57
Tabs
• Tabs allow a more structured organization of content
• The user can easily navigate between one tab and another
• To have separate containers, you can use the tabs
➢ st.tabs(tabs)

• The tabs parameter is a list of strings, each representing the name of


a tab
• The first tab is the one selected by default
• As with columns, returns a list of containers
• Accepts the with notation

58
Tabs example

59
Expander
• Expanders allow you to define containers that the user can choose whether to
open or close
➢ st.expander(label, expanded=False)

• The label parameter represents the name of the expander


• The expanded parameter represents the default state of the expander, whether
open or closed

60
Editing Themes
• You can change the style and colors of the interface to create a
custom application
• From the menu go to Settings and then to Theme
• You can choose between Light and Dark mode or change them by
creating your own theme (changing the colors and font)
• In this way you can experiment live your customizations before
copying them into the configuration file within the section [theme]

61

You might also like