matplotlib 简化(无数据的图形输出)

3htmauhk  于 2023-01-02  发布在  其他
关注(0)|答案(2)|浏览(150)

我想用streamlit实现图表的输出,有模型和初始数据,以前的图表是在Speeder,PyCharm,Colab中显示的,但是在这里不起作用,显示的只是空的,像一张白纸。
协调员:

以下是它的输出localhost 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
chhqkbe1

chhqkbe11#

因此,你的错误在于,你从来没有调用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)

lbsnaicq

lbsnaicq2#

2020年12月1日之后,Streamlit将移除不带任何参数调用st.pyplot()的功能,它需要使用Matplotlib的全局图形对象,而该对象不具备线程安全性。
用fig对象代替st.pyplot(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)

相关问题