Streamlit(无数据图输出)

Streamlit (graph output without data)

我想用streamlit实现图表的输出,有一个模型和初始数据,以前图表在Speeder、PyCharn和Colab中显示,但在这里它不起作用,显示只是空的,就像一个白色 sheet.

Colab

这是它输出的 localhost streamlit

Streamlit

def SIR(y, t, N, beta, gamma):
    S, I, R = y
    dSdt = -beta * S * I / N
    dIdt = beta * S * I / N - gamma * I
    dRdt = gamma * I
    return dSdt, dIdt, dRdt

N = 1000
beta = 1.0
D = 4.0
gamma = 1.0 / D

S0, I0, R0 = 999, 1, 0

t = np.linspace(0, 49, 50)
y0 = S0, I0, R0

ret = odeint(SIR, y0, t, args=(N, beta, gamma))
S, I, R = ret.T

def plotsir(t, S, I, R):
  f, ax = plt.subplots(1,1,figsize=(10,4))
  ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible')
  ax.plot(t, I, 'y', alpha=0.7, linewidth=2, label='Infected')
  ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered')

  ax.set_xlabel('Time (days)')

  ax.yaxis.set_tick_params(length=0)
  ax.xaxis.set_tick_params(length=0)
  ax.grid(b=True, which='major', c='w', lw=2, ls='-')
  legend = ax.legend()
  legend.get_frame().set_alpha(0.5)
  for spine in ('top', 'right', 'bottom', 'left'):
      ax.spines[spine].set_visible(False)
      plt.show()


st.pyplot(plt)

正在导入:

import streamlit as st
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

所以你的错误是你从来没有调用 plotsir(t, S, I, R)。 plt.show() 不适用于 streamlit。请改用 st.pyplot()。工作代码:

import streamlit as st
from scipy.integrate import odeint
import numpy as np
import matplotlib.pyplot as plt

def SIR(y, t, N, beta, gamma):
    S, I, R = y
    dSdt = -beta * S * I / N
    dIdt = beta * S * I / N - gamma * I
    dRdt = gamma * I
    return dSdt, dIdt, dRdt

N = 1000
beta = 1.0
D = 4.0
gamma = 1.0 / D

S0, I0, R0 = 999, 1, 0

t = np.linspace(0, 49, 50)
y0 = S0, I0, R0

ret = odeint(SIR, y0, t, args=(N, beta, gamma))
S, I, R = ret.T

def plotsir(t, S, I, R):
  f, ax = plt.subplots(1,1,figsize=(10,4))
  ax.plot(t, S, 'b', alpha=0.7, linewidth=2, label='Susceptible')
  ax.plot(t, I, 'y', alpha=0.7, linewidth=2, label='Infected')
  ax.plot(t, R, 'g', alpha=0.7, linewidth=2, label='Recovered')

  ax.set_xlabel('Time (days)')

  ax.yaxis.set_tick_params(length=0)
  ax.xaxis.set_tick_params(length=0)
  ax.grid(b=True, which='major', c='w', lw=2, ls='-')
  legend = ax.legend()
  legend.get_frame().set_alpha(0.5)
  for spine in ('top', 'right', 'bottom', 'left'):
      ax.spines[spine].set_visible(False)
      st.pyplot()

plotsir(t, S, I, R)

2020 年 12 月 1 日之后,Streamlit 将取消不带任何参数调用 st.pyplot() 的功能。需要使用Matplotlib的全局图形对象,不是线程安全的。

而是 st.pyplot(fig) 与 fig 对象。示例:

>>> fig, ax = plt.subplots()
>>> ax.scatter([1, 2, 3], [1, 2, 3]) 
>>>    ... other plotting actions ...
>>> st.pyplot(fig)

这意味着提供的解决方案中的“f”变量...

f, ax = plt.subplots(1,1,figsize=(10,4))

...必须像 st.pyplot() 的参数一样传递,在函数的末尾像这样:

st.pyplot(f)