【发布时间】:2021-04-04 16:49:58
【问题描述】:
我有这个程序。它使用Lotka-Volterra ODE 来预测给定时间段内的捕食者和猎物种群。
import random
import numpy as np
import matplotlib.pyplot as plt
from scipy import integrate
# note: model parameters are randomly generated
alpha = random.random() * 0.8
beta = random.random() * 0.003
delta = random.random() * 0.004
gamma = random.random() * 0.8
def f(xy, t):
'''Lotka-Volterra ODE model'''
x, y = xy
dxdt = alpha * x - beta * x * y
dydt = delta * x * y - gamma * y
return [dxdt, dydt]
xy0 = [600, 400]
t = np.linspace(0, 50, 250)
xy_t = integrate.odeint(f, xy0, t)
names = ['prey', 'predator']
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].plot(t, xy_t[:, 0], 'r', label="Prey")
axes[0].plot(t, xy_t[:, 1], 'b', label="Predator")
axes[0].set_xlabel("Time")
axes[0].set_ylabel("Number of animals")
axes[0].legend()
axes[1].plot(xy_t[:,0], xy_t[:, 1], 'k')
axes[1].set_xlabel("Number of prey")
axes[1].set_ylabel("Number of predators")
plt.tight_layout()
plt.show()
这是我的代码产生的结果:
我希望能够...
- 在我的计算机上将我的 matplotlib 图表保存为 pdf 文件。我可以通过使用 matplotlib 来做到这一点:
from matplotlib.backends.backend_pdf import PdfPages
with PdfPages('chart_01.pdf') as pdf:
names = ['prey', 'predator']
fig, axes = plt.subplots(1, 2, figsize=(8, 4))
axes[0].plot(t, xy_t[:, 0], 'r', label="Prey")
axes[0].plot(t, xy_t[:, 1], 'b', label="Predator")
axes[0].set_xlabel("Time")
axes[0].set_ylabel("Number of animals")
axes[0].legend()
axes[1].plot(xy_t[:,0], xy_t[:, 1], 'k')
axes[1].set_xlabel("Number of prey")
axes[1].set_ylabel("Number of predators")
plt.tight_layout()
pdf.savefig(bbox_inches='tight')
- 创建多个图表,这些图表源自重复的模拟运行。我不知道该怎么做,但这里有一些伪代码:
alpha, beta, delta, gamma <-- random
RUNS = 10 # 10 runs means 10 pdf files
for i in RUNS:
data <-- integrate Lotka-Voltera ODE
filename <-- 'chart_0x.pdf'
pdf = create_pdf(filename)
pdf.write_data(data)
我的想法是,运行 10 次后,我最终将获得 10 个 pdf。这些 pdf 文件的名称将是 chart_01.pdf、chart_02.pdf、...chart_10.pdf。我希望我可以使用os 模块来做到这一点,但我担心我不知道如何有效地做到这一点。
过去有没有人做过这样的事情?非常感谢您的反馈。
澄清:我不是在寻求有关 ODE 建模的帮助(尽管我不介意任何有这方面经验的人提供一些建议)。我引入它只是为了为我正在尝试做的事情提供一些背景信息。我的问题纯粹是关于如何生成具有相似名称的多个文件。
【问题讨论】:
标签: python matplotlib file-io output