简体   繁体   English

在一个python脚本中将多个图保存到不同的pdf文件

[英]Saving multiple plots to different pdf files within one python script

Here's the current code I have. 这是我当前的代码。 It's supposed to plot multiple plots onto 2 different graphs, which it does correctly (the outputs of plt.show() are as they should be), but when I go to check the files generated, the same figure is saved in both graph1.pdf and graph2.pdf , and it's the one that should only be in graph1.pdf . 它应该将多个图绘制到2个不同的图形上,并且可以正确执行( plt.show()的输出与plt.show()的一样),但是当我检查生成的文件时,两个图形1中都保存了相同的图形graph1.pdfgraph2.pdf ,并且应该只在graph1.pdf I tried using pdf.clf() before saving the second plot and that only results in the said plot saving blank while the first still saves correctly. 我尝试在保存第二个图之前使用pdf.clf() ,这只会导致所述图保存空白,而第一个图仍正确保存。 Any idea what I'm missing? 知道我缺少什么吗?

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

pdf = plt.figure()


phi_w_0 = [1.5,0]
damp = [0.02 , 0.05 , 0.1 , 0.2]

t = np.linspace(0,200,1000)

def f(w,t):
    return [w[1] , -(B*w[1]) + np.sin(w[0])] 

for B in damp:
    result = odin(f , phi_w_0 , t)
    plt.plot(t , result[:,1] , label='$ \\beta = $ %1.2lf ' % B)

plt.legend()
plt.xlabel('$ \\tau $')
plt.ylabel('$ \\phi $')
plt.show()
pdf.savefig("graph1.pdf")

plt.close()

def g(w,t): 
    return [w[1] , -(B*w[1]) + np.sin(w[0])]

for B in damp:
    result = odin(g , phi_w_0 , t)
    plt.plot(t , result[:,1] , label='$ \\beta = $ %1.2lf ' % B)

plt.legend()
plt.xlabel('$ \\tau $')
plt.ylabel('E')
plt.show()
pdf.savefig("graph2.pdf")
pdf.clf()
pdf = plt.figure()

solved it. 解决了。 Turns out I was on the right track with thinking I have to clear it, but I didn't realize I have to call it again afterwards. 原来我认为自己必须清除它才是对的,但我没有意识到以后必须再次调用它。 Thank you! 谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM