Finishing touches – adding text to Streamlit
Our app is functional, but it is missing a lot of nice touches. We talked earlier about the st.write()
function, which the Streamlit docs call the Swiss Army knife of Streamlit commands. Almost whatever we wrap st.write()
around will work by default and it should be our go-to function if we’re not sure of the best path forward.
Other than st.write()
, we also can utilize other built-in functions that format our text for us, such as st.title()
, st.header()
, st.markdown()
, and st.subheader()
. Using these five functions helps to format text in our Streamlit apps easily and keeps sizing consistent for bigger apps.
More specifically, st.title()
will place a large block of text in our app, st.header()
uses a slightly smaller font than st.title()
, and st.subheader()
uses an even smaller one. Other than those three, st.markdown()
will allow anyone already familiar with Markdown to use the popular markup language in our Streamlit apps. Let’s try a couple of them in the following code:
import streamlit as st
import numpy as np
import matplotlib.pyplot as plt
st.title('Illustrating the Central Limit Theorem with Streamlit')
st.subheader('An App by Tyler Richards')
st.write(('This app simulates a thousand coin flips using the chance of heads input below,'
'and then samples with replacement from that population and plots the histogram of the'
' means of the samples in order to illustrate the central limit theorem!'))
perc_heads = st.number_input(
label='Chance of Coins Landing on Heads', min_value=0.0, max_value=1.0, value=.5)
binom_dist = np.random.binomial(1, perc_heads, 1000)
list_of_means = []
for i in range(0, 1000):
list_of_means.append(np.random.choice(
binom_dist, 100, replace=True).mean())
fig, ax = plt.subplots()
ax = plt.hist(list_of_means)
st.pyplot(fig)
The preceding code adds a large title (st.title()
), adds a smaller subheader below (st.subheader()
), and then adds some even smaller text below the subheader (st.write()
). We also separated the long string of text in the preceding code block into three smaller strings for readability and to make it easier to edit in our text editor. It should look like the following screenshot. Note that because we are using randomly generated data for this histogram, it is OK (and expected!) if your histogram looks slightly different:
Figure 1.9: The central limit theorem application
And that concludes our illustration of the central limit theorem. Go ahead and try out the other options that Streamlit has for writing text (like st.markdown()
, which interprets and writes Markdown-style text in your Streamlit app) to further explore app creation.