可選背景關系隨意跳過:我目前正在使用 cartopy 和 matplotlib 來讀取和在地圖上繪制天氣模型資料。我正在繪制三個不同的領域:溫度、風和表面壓力。我分別使用輪廓、倒鉤和輪廓來繪制每個欄位。我想要每個欄位一張影像,然后我想要一張包含所有三個欄位的影像,覆寫在一張地圖上。目前我這樣做是通過單獨繪制每個欄位,保存每個單獨的影像,然后在單個軸和新無花果上重新繪制所有三個欄位,然后保存該無花果。由于繪制資料需要一段時間,我希望能夠繪制每個單個欄位,然后將軸組合成一個最終影像。
我希望能夠組合多個 matplotlib 軸而無需重新繪制軸上的資料。我不確定這是否可行,但這樣做會節省大量時間和性能。我正在談論的一個例子:
from matplotlib import pyplot as plt
import numpy as np
x1 = np.linspace(0, 2*np.pi, 100)
x2 = x1 5
y = np.sin(x1)
firstFig = plt.figure()
firstAx = firstFig.gca()
firstAx.scatter(x1, y, 1, "red")
firstAx.set_xlim([0, 12])
secondFig = plt.figure()
secondAx = secondFig.gca()
secondAx.scatter(x2, y, 1, "blue")
secondAx.set_xlim([0, 12])
firstFig.savefig("1.png")
secondFig.savefig("2.png")
這將生成兩個影像,1.png 和 2.png。


是否可以保存類似于以下內容的第三個檔案 3.png,但無需scatter再次呼叫,因為對于我的資料集,實際繪圖需要很長時間?

uj5u.com熱心網友回復:
如果您只想保存繪圖的影像并且不打算進一步使用Figure物件,則可以在保存“2.png”后使用以下內容。
# get the scatter object from the first figure
scatter = firstAx.get_children()[0]
# remove it from this collection so you can assign it to a new axis
# the axis reassignment will raise an error if it already belongs to another axis
scatter.remove()
scatter.axes = secondAx
# now you can add it to your new axis
secondAx.add_artist(scatter)
secondFig.savefig("3.png")
這會修改兩個圖形,因為它從一個圖形中洗掉了散點并將其添加到另一個圖形中。如果出于某種原因您想保留它們,您可以將 的內容復制secondFig到一個新的,然后將散點添加到其中。但是,這仍然會修改第一個圖,因為您必須從那里洗掉散點圖。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/385782.html
標籤:Python matplotlib
