gpt4 book ai didi

python - matplotlib for 循环显示、保存和重绘所有图

转载 作者:太空宇宙 更新时间:2023-11-04 08:58:48 25 4
gpt4 key购买 nike

这是我的python代码,

import numpy as np
import matplotlib.pyplot as plt
from pylab import *
from matplotlib.pyplot import savefig


a = np.genfromtxt('do_cv.csv', skiprows = 1, delimiter = ',')
for i in xrange(2):
t = a[i+1:(i+1)*60, 2]
z = a[i+1:(i+1)*60, 3]
est_z = a[i+1:(i+1)*60, 6]
figure(i+1)
plt.plot(t, z, 'bo-', t, est_z, 'go-')
plt.xlabel('time')
plt.ylabel('data value')
plt.grid(True)
plt.legend(['sample data', 'estimated sample data'])
plt.savefig('test + str(i).png')


plt.show()

然后出现2​​个窗口,像这样,

enter image description here enter image description here

图 2 包含图 1 的绘图,如何在第二个循环开始之前重新绘制绘图?我的文件夹中只保存了 1 个 png 文件。

如何修改我的代码并得到我想要的结果?请给我一些建议,非常感谢。

最佳答案

你应该给自己写一个辅助函数:

def my_plotter(ax, t, z, est_z):
ln1 = ax.plot(t, z, 'bo-', label='sample data')
ln2 = ax.plot(t, est_z, 'go-', label='estimated sample data')
ax.xlabel('time')
ax.ylabel('data value')
ax.grid(True)
ax.legend()
return ln1 + ln2

for i in xrange(2):
# get the data
t = a[i+1:(i+1)*60, 2]
z = a[i+1:(i+1)*60, 3]
est_z = a[i+1:(i+1)*60, 6]
# make the figure
fig, ax = plt.subplots()
# do the plot
my_plotter(ax, t, z, est_Z)
# save
fig.savefig('test_{}.png'.format(i))

现在,如果您决定将这两个图作为子图放置,您所要做的就是:

# make one figure with 2 axes
fig, ax_lst = plt.subplots(1, 2)

for i, ax in zip(xrange(2), ax_lst):
# get the data
t = a[i+1:(i+1)*60, 2]
z = a[i+1:(i+1)*60, 3]
est_z = a[i+1:(i+1)*60, 6]
# do the plot
my_plotter(ax, t, z, est_Z)
# save the figure with both plots
fig.savefig('both.png')

关于python - matplotlib for 循环显示、保存和重绘所有图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27693039/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com