How to Use Streamlit’s st.write Function to Improve Your Streamlit Dashboard
The Swiss Army Knife of Streamlit Functions
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.
- Getting Started With Streamlit Web Based Applications
- Creating True Multi-Page Streamlit Apps — The New Way (2022)
- Getting Started With Streamlit: 5 Functions You Need to Know When Starting Out
- The Streamlit Colour Picker: An Easy Way to Change Chart Colours on Your Streamlit Dashboard
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')
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)
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)
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:
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.
This generates the multi-line text output like so. Notice that the line spacing is much smaller than in the previous example.
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.
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}}
$$
""")
If you are unsure about how to do something in LaTeX, here are a few resources to help:
- Build a LaTeX Equation using Codecogs Editor
- Overleaf Reference Guide for Mathematical Expressions
- Wikibooks Guide on LaTeX for Mathematics
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
```
""")
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())
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 )
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.
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:')
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