st.write
allows writing text and arguments to the Streamlit app.
In addition to being able to display text, the following can also be displayed via the st.write()
method:
- Prints strings; works like
st.markdown()
- Displays a Python
dict
- Displays
pandas
DataFrame can be displayed as a table - Plots/graphs/figures from
matplotlib
,plotly
,altair
,graphviz
,bokeh
- And more (see st.write on API docs)
A simple app showing the various ways on how to use the st.write()
method for displaying text, numbers, DataFrames and plots.
The deployed Streamlit app should look something like the one shown in the below link:
Here's how to use st.write:
import numpy as np
import altair as alt
import pandas as pd
import streamlit as st
st.header('st.write')
# Example 1
st.write('Hello, *World!* :sunglasses:')
# Example 2
st.write(1234)
# Example 3
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
st.write(df)
# Example 4
st.write('Below is a DataFrame:', df, 'Above is a dataframe.')
# Example 5
df2 = pd.DataFrame(
np.random.randn(200, 3),
columns=['a', 'b', 'c'])
c = alt.Chart(df2).mark_circle().encode(
x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
st.write(c)
The very first thing to do when creating a Streamlit app is to start by importing the streamlit
library as st
like so:
import streamlit as st
This is followed by creating a header text for the app:
st.header('st.write')
Example 1 Its basic use case is to display text and Markdown-formatted text:
st.write('Hello, *World!* :sunglasses:')
Example 2 As mentioned above, it can also be used to display other data formats such as numbers:
st.write(1234)
Example 3 DataFrames can also be displayed as follows:
df = pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
})
st.write(df)
Example 4 You can pass in multiple arguments:
st.write('Below is a DataFrame:', df, 'Above is a dataframe.')
Example 5 Finally, you can also display plots as well by passing it to a variable as follows:
df2 = pd.DataFrame(
np.random.randn(200, 3),
columns=['a', 'b', 'c'])
c = alt.Chart(df2).mark_circle().encode(
x='a', y='b', size='c', color='c', tooltip=['a', 'b', 'c'])
st.write(c)
Now that you have created the Streamlit app locally, it's time to deploy it to Streamlit Cloud as will be explained soon in an upcoming challenge.
Because this is the first week of your challenge, we provide the full code (as shown in the code box above) and solution (the demo app) right inside this webpage.
Moving forward in the next challenges, it is recommended that you first try implementing the Streamlit app yourself.
Don't worry if you get stuck, you can always take a peek at the solution.
In addition to st.write
, you can explore the other ways of displaying text: