Изменить цвет осей / добавить оси для mathplotlib - PullRequest
0 голосов
/ 08 марта 2020

Я строю график, используя mathplotlib, вот код

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

N = 600
I0 = 1
R0 = 3
S0 = N - I0 - R0 
gamma = 0.07142857
R0 = 3.5
beta = gamma * R0

# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).
beta, gamma = 0.2, 1./10 
# A grid of time points (in days)
t = np.linspace(0, 365, 365)

# The SIR model differential equations.
def deriv(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

# Initial conditions vector
y0 = S0, I0, R0
# Integrate the SIR equations over the time grid, t.
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T

# Plot the data on three separate curves for S(t), I(t) and R(t)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, axis_bgcolor='#dddddd', axisbelow=True)
ax.plot(t, S, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, I, 'm', alpha=0.5, lw=2, label='Infected')
ax.plot(t, R, 'g', alpha=0.5, lw=2, label='Recovered with immunity')
ax.spines['bottom'].set_color('k')
ax.set_xlabel('Time (days)')
ax.set_ylabel('Number of individuals')
ax.set_ylim(0, (N+N/10))
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()

Однако я получаю эту ошибку:

AttributeError: Unknown property axis_bgcolor

Если я удаляю axis_bgcolor='#dddddd' из строки, нарушившей правила и вместо этого использую

ax = fig.add_subplot(111, axisbelow=True)

, я получаю правильный график, но линий осей нет. Как я могу добавить их в?

1 Ответ

1 голос
/ 08 марта 2020

возможно попробуйте следующее:

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

N = 600
I0 = 1
R0 = 3
S0 = N - I0 - R0 
gamma = 0.07142857
R0 = 3.5
beta = gamma * R0

# Contact rate, beta, and mean recovery rate, gamma, (in 1/days).
beta, gamma = 0.2, 1./10 
# A grid of time points (in days)
t = np.linspace(0, 365, 365)

# The SIR model differential equations.
def deriv(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

# Initial conditions vector
y0 = S0, I0, R0
# Integrate the SIR equations over the time grid, t.
ret = odeint(deriv, y0, t, args=(N, beta, gamma))
S, I, R = ret.T

# Plot the data on three separate curves for S(t), I(t) and R(t)
fig = plt.figure(facecolor='w')
ax = fig.add_subplot(111, axisbelow=True)

ax.plot(t, S, 'b', alpha=0.5, lw=2, label='Susceptible')
ax.plot(t, I, 'm', alpha=0.5, lw=2, label='Infected')
ax.plot(t, R, 'g', alpha=0.5, lw=2, label='Recovered with immunity')
ax.spines['bottom'].set_color('k')
ax.set_xlabel('Time (days)')
ax.set_ylabel('Number of individuals')
ax.set_ylim(0, (N+N/10))
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)
#added two lines here setting the face colour of the axes as well as display gridlines
ax.set_facecolor(color='whitesmoke')
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)
plt.show()

Обратите внимание, что я включил следующие 2 строки перед plt.show ()

ax.set_facecolor(color='whitesmoke')
plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2)

Это установит bg_colour осей в вопрос; В дополнение к этому я добавил несколько дополнительных линий сетки, если это то, что вы хотели бы иметь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...