gpt4 book ai didi

python - 将轮廓从一个轴实例复制到另一个

转载 作者:行者123 更新时间:2023-11-28 17:48:27 25 4
gpt4 key购买 nike

我有一种情况,我正在使用 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

另外两个(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() 结果的其他方法?

最佳答案

处理此问题的一种横向方法是重新使用具有轮廓的轴(因为看起来您正在保存每个图形而不是交互式地查看它)。

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

关于python - 将轮廓从一个轴实例复制到另一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14384615/

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