学习streamlit-3

前两篇文章中一直在使用streamlit的方法st.write()来输出文本和参数到页面。

除了文本和参数,st.write()还支持以下内容的显示:

  • 打印字符串,与st.markdown()方法相似。
  • 显示python字典。
  • 显示pandas数据帧,以表格的样式。
  • 画图,来源可以是matplotlib, plotly, altair, graphviz, bokeh
  • 更多特性还在添加。

st.write

下面用一段代码来演示st.write()显示各种内容:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
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)

运行后显示效果:

除了st.write()方法,还可以使用下面几个方法来显示内容:

st.markdown

1
2
3
4
5
import streamlit as st

st.markdown('Streamlit is **_really_ cool**.')
st.markdown(”This text is :red[colored red], and this is **:blue[colored]** and bold.”)
st.markdown(":green[$\sqrt{x^2+y^2}=1$] is a Pythagorean identity. :pencil:")

显示效果:

st.title

1
2
3
4
import streamlit as st

st.title('This is a title')
st.title('A title with _italics_ :blue[colors] and emojis :sunglasses:')

显示效果:

st.header

1
2
3
4
import streamlit as st

st.header('This is a header')
st.header('A header with _italics_ :blue[colors] and emojis :sunglasses:')

显示效果:

st.subheader

1
2
3
4
import streamlit as st

st.subheader('This is a subheader')
st.subheader('A subheader with _italics_ :blue[colors] and emojis :sunglasses:')

显示效果:

st.caption

1
2
3
4
import streamlit as st

st.caption('This is a string that explains something above.')
st.caption('A caption with _italics_ :blue[colors] and emojis :sunglasses:')

显示效果:

st.code

1
2
3
4
5
import streamlit as st

code = '''def hello():
print("Hello, Streamlit!")'''
st.code(code, language='python')

显示效果:

st.text

1
2
3
import streamlit as st

st.text('This is some text.')

显示效果:

st.latex

1
2
3
4
5
6
7
import streamlit as st

st.latex(r'''
a + ar + a r^2 + a r^3 + \cdots + a r^{n-1} =
\sum_{k=0}^{n-1} ar^k =
a \left(\frac{1-r^{n}}{1-r}\right)
''')

显示效果:

magic

streamlit中还有一个”magic”命令,它可以让我们几乎显示任何东西,markdown、数据、图表等等,并且无需输入任何显式命令,只输入要显示的代码行本身就可以显示,比如以下代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
# Draw a title and some text to the app:
'''
# This is the document title

This is some _markdown_.
'''

import pandas as pd
df = pd.DataFrame({'col1': [1,2,3]})
df # 👈 Draw the dataframe

x = 10
'x', x # 👈 Draw the string 'x' and then the value of x

# Also works with most supported chart types
import matplotlib.pyplot as plt
import numpy as np

arr = np.random.normal(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)

fig # 👈 Draw a Matplotlib chart

运行后效果:

视频教程: