avatarAndy McDonald

Summary

The web content provides an in-depth guide on utilizing Streamlit's st.write() function to enhance the presentation of Streamlit dashboards through various text formats, markdown, LaTeX, code blocks, dataframes, and chart figures.

Abstract

The article "How to Use Streamlit’s st.write Function to Improve Your Streamlit Dashboard" delves into the versatility of the st.write() function, emphasizing its role as a fundamental tool in Streamlit for displaying text, formatted text with HTML and CSS, markdown syntax, LaTeX equations, code blocks, Pandas dataframes, and interactive charts. The function is described as the "Swiss Army Knife" of Streamlit due to its ability to handle multiple types of outputs, including the integration of emojis to add personality to the text. The author provides practical examples and encourages readers to explore Streamlit's documentation to further enhance their Streamlit applications. Additionally, the article is part of a series aimed at Streamlit users, offering resources for further learning and engagement with the author's content through subscriptions and memberships.

Opinions

  • The author expresses that the st.write() function is essential for creating engaging and informative Streamlit dashboards.
  • Utilizing HTML and CSS within st.write() is promoted as a way to add color and style to text, making the dashboard more visually appealing.
  • The use of markdown within st.write() is recommended for its simplicity and ease of formatting text.
  • The author suggests that LaTeX, through KaTeX, is a powerful tool within Streamlit for presenting complex mathematical equations in a readable format.
  • Streamlit's ability to render Pandas dataframes interactively is highlighted as a key feature for data analysis within dashboards.
  • The article encourages the use of emojis to make Streamlit apps more engaging and personable.
  • The author advocates for readers to subscribe to their content and consider a Medium membership to support writers and access premium content.

How to Use Streamlit’s st.write Function to Improve Your Streamlit Dashboard

The Swiss Army Knife of Streamlit Functions

Photo by Bram Naus on Unsplash

When starting with Streamlit, one of the first functions you will come across when building your dashboard or app is st.write() . The Streamlit documentation describes this function as the “Swiss Army Knife of Streamlit Commands”.

It is a very versatile function that allows you to display text, emojis, markdown and much more.

Within this article, we are going to explore the ways that the st.write() function can be used to improve your Streamlit dashboards.

This article forms part of a series of articles I am creating on Streamlit. You can explore them at the links below.

Displaying Simple and Formatted Text with st.write

The first and most obvious use of the st.write() command is to display text. If we use the simple example below, we will get that text displayed on our app.

st.write('Here is some simple text')
Result of displaying simple text with st.write. Image by the author.

How to Format and Add Colour to the Text Generated by st.write

The above text looks a little boring. We can spice things up a little by adding some colour. To this, we need to utilise some HTML and CSS knowledge by setting the unsafe_allow_html option to True.

We then create a paragraph using the HTML <p> tag and setting the colour using the style parameter

st.write('<p style="color:red;">Here is some red text</p>', 
unsafe_allow_html=True)
Changing the colour of the font within the st.write function. Image by the author.

If we want to increase the font size, we can add in a font-size

st.write('<p style="font-size:26px; color:red;">Here is some red text</p>',
unsafe_allow_html=True)
Changing the colour and the size of the font within the st.write function. Image by the author.

Splitting Text over Multiple Lines

Instead of having text on a single line, we can display text on multiple lines. The st.write function allows you to pass in a string enclosed in triple single quotes (’’’) or triple double quotes (”””). This syntax is used within Python to allow strings to span multiple lines.

Just using the triple single quotes or triple double quotes is not enough to get our text to span multiple lines when using Streamlit. In order to do this we have to modify the string.

There are a couple of different ways to achieve this.

The first is to use the line break character \n which will push the following line of text onto a new line.

st.write("""This is an example \n
of writing text \n
on multiple lines \n
""")

This generates the following output:

Splitting text over multiple lines with the st.write function. Image by the author.

The second option is to add two spaces at the end of each line. This is commonly applied in markdown language to move the text to a new line.

Adding two spaces at the end of a string allows text to be displayed on multiple lines. Note the two faint dots at the end of each line representing two spaces. Image by the author.

This generates the multi-line text output like so. Notice that the line spacing is much smaller than in the previous example.

Splitting text over multiple lines with the st.write function. Image by the author.

Using Markdown Syntax with st.write

Markdown is a popular markup language that allows writers to apply formatting simply and easily within a plain text format. It is one of my favourite ways to write and is used by numerous note-taking apps such as Obsidian and Notion.

To use markdown within the st.write() function, we simply type it in like so:

st.write('## Markdown')
st.write('Here is some more **markdown** text. *And here is some more in italics*')

The first line creates a second-level heading (H2), and the second line creates some formatted text. Using a double asterisk (**) around the text makes it bold, and a single asterisk (*) makes it italicised.

When we refresh the app, we get the following output.

Example of using markdown syntax with the Streamlit st.write function. Image by the author.

If you want to learn more about how to write using markdown, then check out Basic Syntax Markdown Guide.

The specific type of markdown used by Streamlit is Github Flavoured which is a dialect of markdown and has its own features and nuances.

Create LaTeX / KaTeX Formatted Equations with st.write

LaTeX has been around for a long time (since 1984) and is another form of markup language used for typesetting documents and preparing them for print. In addition to typesetting, it can be used to prepare and format mathematical equations.

Streamlit uses a version of KaTeX to render equations using LaTeX syntax. KaTeX is essentially a Javascript library that is used to render mathematical symbols and equations.

Instead of having equations as linear text — which can be hard to read — we can format them in a way that makes them much more readable.

To display LaTeX equations in Streamlit, we need to surround our equation with two dollar signs ($$) at the start of the equation and two dollar signs at the end.

We can then leverage the power of LaTeX to write our equation.

st.write("""Here is a simple equation using LaTeX
$$
ax^2 + bx + c
$$
""")

st.write(r"""And a slightly more complex equation
$$
Sw = \bigg({\frac{a \cdot Rw}{\phi^m \cdot Rt} \bigg)^\frac{1}{n}}
$$
""")
Example of using KaTeX with the Streamlit st.write function to display simple and more complicated mathematical equations. Image by the author.

If you are unsure about how to do something in LaTeX, here are a few resources to help:

The supported functions used by Streamlit are derived from KaTeX, and the full list of functions can be found here.

Writing Code Blocks

If we are creating an app or dashboard where we want to display code for the user to inspect or learn from, we can use markdown syntax to create a code block. This is achieved using three backticks before, and after the code we want to display.

We can also supply a language to create some syntax highlighting.

st.write("""
```python
if we_want_to_display_code:
    use_back_ticks == True
```
""")
Code block displayed using st.write and markdown syntax. Image by the author.

Using st.write to Display Pandas Dataframes

Pandas dataframes are a commonly used format within data science. They can be used to store, manipulate and create new data.

When building a Streamlit app we will most likely be working with dataframes to handle data. The st.write function can display interactive dataframes by passing in the dataframe object or related methods, such as the describe method.

arr_data = np.random.default_rng().uniform(0, 100, size=(5,4))
df = pd.DataFrame(arr_data, columns=list('ABCD'))

st.write('Displaying the dataframe: `df`')
st.write(df)

st.write('Using the `describe` method:')
st.write(df.describe())
Streamlit app displaying a pandas dataframe and the describe method. Image by the author

Combining Text and Variables with st.write

By using f-strings we can combine both strings and variables in a single output. Streamlit also takes this one step further by allowing us to pass in multiple arguments, which are then combined.

In the example below, we are using f-strings to display the values of a and b and then the final line is combing text with a summation of a+b.

a = 3
b = 3

st.write(f'a is: {a}')
st.write(f'b is: {b}')
st.write('And if we sum them together we get:', a + b )
Combining Text and Variables with Streamlit’s st.write function. Image by the author.

Display Chart Figures with st.write()

Displaying data using charts is a fundamental part of data science and data analytics. It allows us to convey data in a way that is easy for readers to understand and make informed decisions with.

Streamlit handles multiple plotting libraries, including matplotlib, seaborn, altair and plotly.

First, we need to have a data source, which can be from a file or an existing data frame, and second, we need to create our figure. In the example below, I have created a simple random dataset and selected two columns to display in a scatter plot.

The matplotlib figure is then passed into the st.write function.

# Creating a dataframe with random values in 5 columns
arr_data = np.random.default_rng().uniform(0, 100, size=(5,5))
df = pd.DataFrame(arr_data, columns=list('ABCDE'))

# Creating a simple figure
fig, ax = plt.subplots(1,1)
ax.scatter(x=df['A'], y=df['B'])
st.write(fig)

When we run the above code, we get back the following display.

A matplotlib figure displayed using st.write(). Image by the author

Incorporating Emojis

Finally, we can add some interest to our text using emojis. This is easily done by using a colon before and after the emoji name.

st.header('Emojis')
st.write('Emojis can be used to add a bit of character 
to your text :smile: :grin: :thumbsup:')
Displaying emojis within a Streamlit app using st.write(). Image by the author.

Summary

The Streamlit st.write() function is a powerful tool and can be used in many different ways, from writing ordinary text to displaying figures and equations. It certainly lives up to its name as the Swiss Army Knife function of the Streamlit library.

Be sure to check out the documentation on Streamlit Magic to take your app to the next level.

Thanks for reading. Before you go, you should definitely subscribe to my content and get my articles in your inbox. You can do that here! Alternatively, you can sign up for my newsletter to get additional content straight into your inbox for free.

Secondly, you can get the full Medium experience and support thousands of other writers and me by signing up for a membership. It only costs you $5 a month, and you have full access to all of the fantastic Medium articles, as well as the chance to make money with your writing.

If you sign up using my link, you will support me directly with a portion of your fee, and it won’t cost you more. If you do so, thank you so much for your support

Streamlit
Python
Data Science
Dashboard
Data Analysis
Recommended from ReadMedium
avatarTechnocrat
Using Streamlit for UI

32 min read