matplotlib for循环显示,保存和重绘所有图

时间:2014-12-29 17:08:36

标签: python for-loop matplotlib plot

这是我的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文件。

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

2 个答案:

答案 0 :(得分:3)

你在循环的每次迭代时都会覆盖你的png文件,这就是为什么你只有一个。

    plt.savefig('test + str(i).png')

应该是

    plt.savefig('test ' + str(i) + '.png')

答案 1 :(得分:2)

你应该把自己写成辅助函数:

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')