[英]How to add_subplot figure generated from external function with matplotlib
目前,我有三個函數來創建圖形,即get_image_1
、 get_image_2
和get_image_3
,如下面的函數所示。
def get_image_1():
fig, ax = plt.subplots(figsize=(8, 6))
plt.plot(range(10))
fig.savefig('image_1.png')
# return fig
def get_image_2():
fig, ax = plt.subplots(figsize=(8, 6))
plt.plot([0,5,8,9,3,6])
fig.savefig('image_2.png')
# return fig
def get_image_3():
fig, ax = plt.subplots(figsize=(8, 6))
plt.plot([100,5,8,9,3,6])
fig.savefig('image_3.png')
# return fig
為簡單起見,我們只使用簡單的plt.plot()
。
上述函數通過調用
get_image_1()
get_image_2()
get_image_3()
我想顯示這三個圖,如圖所示。
目前,我必須在本地保存每個圖像。 例如,在函數get_image_1
,請注意fig.savefig('image_1.png')
行。
並重新上傳保存的圖像,然后按照下面的代碼將它們組合起來
import matplotlib.pyplot as plt
import cv2 as cv
fig = plt.figure(figsize=(9, 10))
for idx,dpath in enumerate(['image_1.png','image_2.png','image_3.png']):
tt=1
if idx!=2:
sub1 = fig.add_subplot(2, 2, idx + 1)
else:
sub1 = fig.add_subplot(2, 2, (3,4))
image2 = cv.imread(dpath)
sub1.imshow(image2, 'gray')
plt.show()
我想知道如何更有效地進行這項活動。 這樣,完全跳過saved
並重新上傳圖像。
根據評論中的@BigBen 建議。
修改函數以接受axes
參數
def get_image_1(ax):
ax.plot(range(10))
def get_image_2(ax):
ax.plot([0,5,8,9,3,6])
def get_image_3(ax):
ax.plot([100,5,8,9,3,6])
然后,為每個function
調用傳遞axes
參數
fig = plt.figure(figsize=(9, 10))
ax1 = fig.add_subplot(2, 2, 1)
get_image_1(ax1)
get_image_2(fig.add_subplot(2, 2, 2))
get_image_3(fig.add_subplot(2, 2, (3,4)))
plt.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.