3

matplotlibを使用して20以上の異なる画像を作成している状況があります。これは何度も行われます。20枚の画像のそれぞれは、背景に同じ輪郭のセットを持っています。countourf()処理時間を短縮するには、あるAxesインスタンスから別のインスタンスに結果をコピーできると便利です。これを行うために、私はこれを試しました:

#!/bin/env python

import os
import numpy as np
from matplotlib import pyplot as plt

def copycontours():
    #Create figures
    fig1 = plt.figure()
    fig2 = plt.figure()
    fig3 = plt.figure()

    #Create axes
    ax1 = fig1.add_axes((0.05,0.05,0.90,0.90))
    ax2 = fig2.add_axes((0.05,0.05,0.90,0.90))
    ax3 = fig3.add_axes((0.05,0.05,0.90,0.90))

    #Create random data
    data = np.random.normal(25, size=(25,25))

    #Add contours to first axes instance and save image
    contours = ax1.contourf(data)
    fig1.savefig('test.png')

    #Add contours to second axes instance from first axes instance
    for collection in ax1.collections:
        ax2.add_collection(collection)
    fig2.savefig('test2.png')

    #Add contours to third axes instance from 
    for collection in contours.collections:
        ax3.add_collection(collection)
    fig3.savefig('test3.png')

    os.system('display test.png &')
    os.system('display test2.png &')
    os.system('display test3.png &')

if __name__ == '__main__':
    copycontours()

最初の図(test.png)は正しく見えます。軸の範囲は0〜25で、ドメイン全体が塗りつぶされます。

test1.png

他の2つ(test2.png、test3.png)の出力は異なります。それらの軸の範囲は0から1で、等高線領域は0.0から約7.9の領域のみを塗りつぶします。

test2.png

を介して軸制限をリセットするax2.set_xlim(0,25)ax2.set_xlim(0,25)、軸範囲が変更されますが、より大きな問題は修正されません。

test3.png

この問題を修正する方法や、結果を別の方法で再利用するための別の方法について誰かが考えていますcontourf()か?

4

1 に答える 1

2

これに対処する横向きの方法は、輪郭を持つ軸を再利用することです (すべての図を保存していて、これを対話的に見ていないように見えるため)。

ax = fig.add_axes()
ax.contourf(..)
keep_lst = ax.get_children()[:] # state of the figure before adding anything extra

for plot_pram in conditions:
    # your plotting code

    fig.savefig()

    cur_children = ax.get_children()[:]
    # all the extra stuff you just plotted on it
    for a in cur_children:
        if a not in keep_lst:
            # if the artist isn't part of the initial set up, remove it
            a.remove()
于 2013-01-18T00:20:41.570 に答える