[英]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.