显示一个matplotlib.pyplot图形。

重要

你必须安装 matplotlib 才能使用此命令。

函数签名[source]

st.pyplot(fig=None, clear_figure=None, use_container_width=True, **kwargs)

参数

fig (Matplotlib 图)

要渲染的 Matplotlib Figure 对象。请参阅 https://matplotlib.org/stable/gallery/index.html 获取示例。

注意

当未指定此参数时,此函数将渲染全局的 Matplotlib 图对象。然而,此功能已被弃用,并将在后续版本中移除。

clear_figure (bool)

如果为True,图形在渲染后将被清除。 如果为False,图形在渲染后不会被清除。 如果未指定,我们将根据fig的值选择一个默认值。

  • 如果fig已设置,默认为False
  • 如果fig未设置,默认为True。这模拟了Jupyter对matplotlib渲染的处理方式。

use_container_width (bool)

是否用父容器的宽度覆盖图形的原生宽度。如果use_container_widthTrue (默认),Streamlit会将图形的宽度设置为与父容器的宽度匹配。如果use_container_widthFalse,Streamlit会根据绘图库将图表的宽度设置为适合其内容,直到父容器的宽度。

**kwargs (any)

传递给Matplotlib的savefig函数的参数。

示例

import streamlit as st
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)

st.pyplot(fig)

Matplotlib 支持多种类型的“后端”。如果您在使用 Matplotlib 与 Streamlit 时遇到错误,请尝试将后端设置为“TkAgg”:

echo "backend: TkAgg" >> ~/.matplotlib/matplotlibrc

欲了解更多信息,请参阅 https://matplotlib.org/faq/usage_faq.html

priority_high

警告

Matplotlib 在线程中表现不佳。因此,如果您正在使用Matplotlib,您应该像下面的代码片段所示那样用锁包装您的代码。当您部署和共享您的应用程序时,这个Matplotlib错误更加明显,因为那时您更有可能获得并发用户。

from matplotlib.backends.backend_agg import RendererAgg _lock = RendererAgg.lock with _lock: fig.title('This is a figure)') fig.plot([1,20,3,40]) st.pyplot(fig)
forum

还有问题吗?

我们的 论坛 充满了有用的信息和Streamlit专家。