单个matplotlib figu中的多个绘图

2024-03-29 07:20:22 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python脚本中,我有一组2dnumpy float数组,比如n1、n2、n3和n4。对于每个这样的数组,我有两个整数值offset iu x和offset iu y(用1、2、3和4替换I)。在

目前,我可以使用以下脚本为一个NumPy数组创建一个映像:

   def make_img_from_data(data)
        fig = plt.imshow(data, vmin=-7, vmax=0)
        fig.set_cmap(cmap)
        fig.axes.get_xaxis().set_visible(False)
        fig.axes.get_yaxis().set_visible(False)
        filename = "my_image.png"
        plt.savefig(filename, bbox_inches='tight', pad_inches=0)
        plt.close()

现在我想把每个数组看作是一个更大图像的一个平铺,并且应该根据offset iu x/y的值来放置,最后写一个数字而不是4(在我的例子中)。一般来说,我对MatplotLib和Python非常陌生。我怎么能做到呢?在

我还注意到上面的脚本生成的图像是480x480像素,不管原始NumPy数组的大小。如何控制生成图像的大小?在

谢谢


Tags: 图像numpy脚本falsedatagetfigplt
2条回答

如果我理解正确,您似乎在寻找subplots。请查看thumbnail gallery中的示例。在

您可能需要考虑的add_axes函数matplotlib.pyplot. 在

下面是一个肮脏的例子,基于你想要达到的目标。 请注意,我已经选择了偏移量的值,因此示例可以工作。你必须弄清楚如何转换每幅图像的偏移值。在

import numpy as np
import matplotlib.pyplot as plt

def make_img_from_data(data, offset_xy, fig_number=1):
    fig.add_axes([0+offset_xy[0], 0+offset_xy[1], 0.5, 0.5])
    plt.imshow(data)

# creation of a dictionary with of 4 2D numpy array
# and corresponding offsets (x, y)

# offsets for the 4 2D numpy arrays
offset_a_x = 0
offset_a_y = 0
offset_b_x = 0.5
offset_b_y = 0
offset_c_x = 0
offset_c_y = 0.5
offset_d_x = 0.5
offset_d_y = 0.5

data_list = ['a', 'b', 'c', 'd']
offsets_list = [[offset_a_x, offset_a_y], [offset_b_x, offset_b_y],
                [offset_c_x, offset_c_y], [offset_d_x, offset_d_y]]

# dictionary of the data and offsets
data_dict = {f: [np.random.rand(12, 12), values] for f,values in zip(data_list, offsets_list)}

fig = plt.figure(1, figsize=(6,6))

for n in data_dict:
    make_img_from_data(data_dict[n][0], data_dict[n][1])

plt.show()

产生:

this result

相关问题 更多 >