【问题标题】:File Output: Writing Data for Multiple Executions?文件输出:为多次执行写入数据?
【发布时间】: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.pdfchart_02.pdf、...chart_10.pdf。我希望我可以使用os 模块来做到这一点,但我担心我不知道如何有效地做到这一点。

过去有没有人做过这样的事情?非常感谢您的反馈。

澄清:我不是在寻求有关 ODE 建模的帮助(尽管我不介意任何有这方面经验的人提供一些建议)。我引入它只是为了为我正在尝试做的事情提供一些背景信息。我的问题纯粹是关于如何生成具有相似名称的多个文件。

【问题讨论】:

    标签: python matplotlib file-io output


    【解决方案1】:

    除了使用matplotlib.backends.backend_pdf,您可以使用图形名称中的适当扩展名直接将图像保存为pdf。比如:

    
    for i in range(10):
        fig, ax = plt.subplots()
        ax.plot(data)
        fig.savefig(f"chart_{i}.pdf") 
        fig.clear()
    
    

    如果您不想每次都制作新图形,您可以更新数据。如果您有相当复杂的图形准备,这将很有用

    fig, ax = plt.subplots()
    myplot, = ax.plot(data)
    
    for i in range(10):
        ndata = data * i # a new data to plot
        myplot.set_ydata(ndata)
        fig.savefig(f"chart_{i}.pdf")
    

    【讨论】:

    • 嗨,krm!这是有道理的。非常感谢!
    猜你喜欢
    • 2020-05-24
    • 2014-08-17
    • 2018-11-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多