【问题标题】:matplotlib for loop to show, save and redraw all plotsmatplotlib for 循环显示、保存和重绘所有绘图
【发布时间】:2014-12-29 17:08:35
【问题描述】:

这是我的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​​个窗口,像这样,

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

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

【问题讨论】:

    标签: python for-loop matplotlib plot


    【解决方案1】:

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

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

    【讨论】:

    • 我已经尝试了你的两个代码,但在第二个图中我仍然得到相同的结果,其中包含第一个图中的点。
    • 那是因为你选择的数据也是错误的。您正在退出 [1:60],然后是 [2:120]
    • 感谢您的提醒,这解决了我的问题!
    【解决方案2】:

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

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

    应该是

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-09
      相关资源
      最近更新 更多