pythonStreamlit库⽰例
# Pycharm V2021
# 解释器 Python 3.7 D:\ProgramData\
# -*- coding:utf-8
# author :RainChang
# 2021/10/28,13:42
# 操作说明:cw.hubwiz/card/c/streamlit-manual/
# ⽰例来源:blog.csdn/qq_44747847/article/details/116462041?spm=1001.2101.3001.6650.5&utm_medium=distribute.-task-blog-2%7Edefault%_search_link&depth_1-utm_source=distribute.-task-blog-2%7Edefault%_search_link
# 在Terminal 运⾏Streamlit run  filename.py
import time
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import streamlit as st
from PIL import Image
import altair as alt
st.title("This is my first app")
st.write("hello")
st.write("Here's our first attempt at using data to create a table:")
df = pd.DataFrame({
'first column': [5, 6, 7, 8],
'second column': [50, 60, 70, 80]
})
st.write(pd.DataFrame({
'first column': [1, 2, 3, 4],
'second column': [10, 20, 30, 40]
}))
# 其中df定义的位置,并不影响最后的输出位置!
# df
# 绘制图表
# 折线图
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
st.line_chart(chart_data)
# 区域图的可视化
# “streamlit”中的“area_chart”⽅法显⽰区域图,⽅法原型和折线图⽤到的⽅法⼀致,所以这⾥就不做过多的赘述,例如下⾯的代码
chart_data = pd.DataFrame(
np.random.randn(50, 3),
columns=['a', 'b', 'c'])
st.area_chart(chart_data)
# 柱状图的可视化
# “streamlit”的“bar_chart()”⽅法显⽰柱状图,例如下⾯的代码
chart_data = pd.DataFrame(np.random.randn(50, 3),
columns=['a', 'b', 'c'])
st.bar_chart(chart_data)
# 显⽰图像
# “streamlit”中的“image”⽅法可以⽤来显⽰⼀张或多张图像,其中的⽅法原型,
# “streamlit”中的“image”⽅法可以⽤来显⽰⼀张或多张图像,其中的⽅法原型,
# streamlit.image(image, caption=None, width=None, use_column_width=False, clamp=False, channels='RGB', format='JPEG') # 参数:
# image:要显⽰的图像,类型可以是numpy.ndarray, [numpy.ndarray], BytesIO, str, 或 [str]) – 单⾊图像为(w,h) 或 (w,h,1)
# 彩⾊图像为(w,h,3)
# RGBA图像为(w,h,4)
# 也可以指定⼀个图像url,或url列表
# caption:图像标题,字符串。如果显⽰多幅图像,caption应当是字符串列表
# width :图像宽度,None表⽰使⽤图像⾃⾝宽度
# use_column_width:如果设置为True,则使⽤列宽作为图像宽度
# clamp:是否将图像的像素值压缩到有效域(0~255),仅对字节数组图像有效。
# channels:图像通道类型,'RGB' 或 'BGR',默认值:RGB
# format:图像格式:'JPEG' 或'PNG'),默认值:JPEG
# image = Image.open('123.jpg')
# st.image(image, caption='刘雅鸣视察葫芦岛', use_column_width=True)
#
image = Image.open('123.jpg')
st.image(image, caption='Sunrise by the mountains')
# 绘制⼀个地图
# map_data = pd.DataFrame(
#    np.random.randn(1000, 2) / [50, 50] + [37.76, -122.4],
#    columns=['lat', 'lon'])
#
# st.map(map_data)
# 调整地图的中⼼到沈阳
map_data = pd.DataFrame(
np.random.randn(1000, 2) / [50, 50] + [41.8, 123.4],
columns=['lat', 'lon'])
st.map(map_data)
# 增加交互性,显⽰单选框
# st.checkbox()**单选框,更多请查询API reference
if st.checkbox('Show dataframe'):
chart_data = pd.DataFrame(
np.random.randn(20, 3),
columns=['a', 'b', 'c'])
chart_data
# 增加复选框
option = st.selectbox(
random python
'Which number do you like best?',
df['first column'])
'You selected: ', option
# 调整布局
# 为了使得你的webApp更加好看,你可以将⼀些不必要的内容放置到其他区域。这样可以使得你的webApp居中。
# **st.sidebar()**将刚才的边框设置在左侧
# tips:可以发现每次选择不同的数字,整个页⾯都会刷新,包括刚才设置的地图上的点也会跟着刷新,和刚才的折线图
add_selectbox = st.sidebar.selectbox(
"How would you like to be contacted?",
("Email", "Home phone", "Mobile phone")
)
# 你也可以使⽤st.beta_columns来并排布置⼩部件,或者使⽤st.beta_expander来隐藏⼤型内容以节省空间
left_column, right_column = st.beta_columns(2)
pressed = left_column.button('Press me?')
pressed = left_column.button('Press me?')
if pressed:
right_column.write("Woohoo!")
expander = st.beta_expander("FAQ")
expander.write("Here you could put in some really, really ")
# 添加进度条
# 当在⼀个应⽤程序中添加长期运⾏的计算时,你可以使⽤st.progress()来实时显⽰状态。# ⾸先,让我们导⼊时间。我们将使⽤time.sleep()⽅法来模拟⼀个长期运⾏的计算
'Starting a '
# Add a placeholder
latest_iteration = st.empty()
bar = st.progress(0)
for i in range(100):
# Update the progress bar with each iteration.
(f'Iteration {i + 1}')
bar.progress(i + 1)
time.sleep(0.1)
'...and now we\'re done!'
# 现在让我们使⽤st.echo()让中间部分的代码可视化:
# st.echo - 显⽰应⽤源代码
# 在with块中使⽤streamlit的echo⽅法显⽰应⽤源代码,然后执⾏。
def get_user_name():
return 'John'
ho():
# Everything inside this block will be both printed to the screen
# and executed.
def get_punctuation():
return ''
greeting = "Hi there, "
value = get_user_name()
punctuation = get_punctuation()
st.write(greeting, value, punctuation)
# And now we're back to _not_ printing to the screen
foo = 'bar'
st.write('Done!')
# st.pyplot - 显⽰pyplot图表
# streamlit的pyplot⽅法显⽰指定的matplotlib.pyplot图表。
#
# ⽅法原型
# streamlit.pyplot(fig=None, **kwargs)
# 参数:
# fig:要使⽤的绘制⾯板,当为None时,使⽤整个绘图区域
# **kwargs :传⼊Matplotlib的savefig函数的关键字参数
fig, ax = plt.subplots()
ax.scatter([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
st.pyplot(fig)
arr = al(1, 1, size=100)
arr = al(1, 1, size=100)
fig, ax = plt.subplots()
ax.hist(arr, bins=20)
st.pyplot(fig)
# st.vega_lite_chart
# Streamlit Version  v1.1.0
# Display a chart using the Vega-Lite library.
df = pd.DataFrame(
np.random.randn(200, 3),
columns=['a', 'b', 'c'])
st.vega_lite_chart(df, {
'mark': {'type': 'circle', 'tooltip': True},
'encoding': {
'x': {'field': 'a', 'type': 'quantitative'},
'y': {'field': 'b', 'type': 'quantitative'},
'size': {'field': 'c', 'type': 'quantitative'},
'color': {'field': 'c', 'type': 'quantitative'},
},
})
# st.altair - 显⽰altair图表
# streamlit的altair⽅法使⽤Altair库显⽰指定的图表。
#
# ⽅法原型
# streamlit.altair_chart(altair_chart, width=0)
# 参数:
#
# altair_chart:要显⽰的Altair图表对象,类型:altair.vegalite.v2.api.Chart
# width:宽度模式,0 表⽰拉伸图表到⽂档宽度,-1表⽰使⽤Altair的默认值,⼤于0表⽰设置的宽度像素。默认值:0。注意如果顶层宽度已定义,那么将覆盖这⾥的设定。
# ⽰例代码
df = pd.DataFrame(
np.random.randn(200, 3),
columns=['a', 'b', 'c'])
c = alt.Chart(df).mark_circle().encode(
x='a', y='b', size='c', color='c')
st.altair_chart(c, use_container_width=True)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。