摘要:# coding: utf-8import matplotlib.pyplot as pltimport numpy as npimport streamlit as starr = np.random.normal(1, 1, size=100)plt.hi
streamlit的pyplot方法显示指定的Matplotlib.pyplot图表。
streamlit.pyplot(fig=None, **kwargs)fig:要使用的绘制面板,当为None时,使用整个绘图区域**kwargs :传入Matplotlib的savefig函数的关键字参数示例:
# coding: utf-8import matplotlib.pyplot as pltimport numpy as npimport streamlit as starr = np.random.normal(1, 1, size=100)plt.hist(arr, bins=20)st.pyplot(plt)运行结果:
Matplotlib支持几种不同的后端。如果你在Streamlit中使用Matplotlib出现问题, 可以尝试将后端设置为 “TkAgg”:
echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrcstreamlit的altair方法使用Altair库显示指定的图表。
streamlit.altair_chart(altair_chart, width=0)altair_chart:要显示的Altair图表对象,类型:altair.vegalite.v2.api.Chartwidth:宽度模式,0 表示拉伸图表到文档宽度,-1表示使用Altair的默认值,大于0表示 设置的宽度像素。默认值:0。注意如果顶层宽度已定义,那么将覆盖这里的设定。import numpy as npimport pandas as pdimport altair as altdf = 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)运行结果:
streamlit的vega_lite_chart方法使用Vega-Lite库显示指定的图表。
streamlit.vega_lite_chart(data=None, spec=None, width=0, **kwargs)data:要显示的数据对象或Vega-Lite图表规格,数据类型可以是:pandas.DataFramepandas.Stylernumpy.ndarrayIterabledictNonespec:Vega-Lite的图表规格,如果在前面data参数已经传入图表规格,这里 必须传入Nonewidth:宽度模式。0表示使用整个文档宽度,-1表示使用Veta-Lite的默认值。 大于0表示要设置的宽度像素。注意如果定义了spec['width'],那么这里的 设置无效**kwargs:与spec参数相同,只是采用关键词参数import pandas as pdimport numpy as npdf = pd.DataFrame(np.random.randn(200, 3),columns=['a', 'b', 'c'])st.vega_lite_chart(df, {'mark': 'circle','encoding': {'x': {'field': 'a', 'type': 'quantitative'},'y': {'field': 'b', 'type': 'quantitative'},'size': {'field': 'c', 'type': 'quantitative'},'color': {'field': 'c', 'type': 'quantitative'},},})运行结果:
streamlit的plotly方法显示可交互的Plotly图表。要在Streamlit 中显示Plotly图表,只需要用plotly_chart调用替代原本 的Plotly的py.plot或py.iplot调用。
Plotly是一个Python的图表库。该方法的参数基本遵循Plotly的plot 函数的定义。你可以在这里查看详细信息:https://plot.ly/python。
streamlit.plotly_chart(figure_or_data, width=0, height=0, sharing='streamlit', **kwargs)figure_or_data :plotly图表数据或matplotlib绘图面板。如果是 matplotlib绘图面板,会将其转化为Plotly绘图面板然后再显示width:图表宽度,单位为像素,或者设置为0,表示使用全部宽度height:图表高度,单位为像素,或者设置为0,表示使用默认高度sharing:共享模式,可选值:streamlit、private、secret、public。设置为 streamlit将图表以及依赖插入Streamlit应用,这意味着可以离线 运行。使用其他设置会发送到Plotly的服务器,然后嵌入Streamlit应用。**kwargs:Plotly的plot方法接受的其他参数示例:
import streamlit as stimport plotly.figure_factory as ffimport numpy as np# Add histogram datax1 = np.random.randn(200) - 2x2 = np.random.randn(200)x3 = np.random.randn(200) + 2# Group data togetherhist_data = [x1, x2, x3]group_labels = ['Group 1', 'Group 2', 'Group 3']# Create distplot with custom bin_sizefig = ff.create_distplot(hist_data, group_labels, bin_size=[.1, .25, .5])# Plot!st.plotly_chart(fig)运行结果:
streamlit的bokeh方法显示可交互的Bokeh图表。要在Streamlit 中显示Bokeh图表,只要在本该调用Bokeh的show方法时调用 st.bokeh_chart即可。
Bokeh是一个Python的图表库,bokeh方法的参数基本遵从Bokeh 的show方法的要求。详情可参考 https://bokeh.pydata.org 。
来源:IT职业教育