单个matplotlib图中的多个图

时间:2012-02-23 09:34:35

标签: python numpy matplotlib

在Python脚本中,我有一组2D NumPy浮点数组,比如说n1,n2,n3和n4。对于每个这样的数组,我有两个整数值offset_i_x和offset_i_y(将i替换为1,2,3和4)。

目前,我可以使用以下脚本为一个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_i_x / y值放置,最后写一个图而不是4个(在我的例子中)。我对MatplotLib和Python很新。我怎么能这样做?

此外,我注意到上面的脚本生成480x480像素的图像,无论原始NumPy阵列的大小。如何控制生成图像的大小?

由于

2 个答案:

答案 0 :(得分:4)

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

以下是一个基于您想要实现的内容的肮脏示例。 请注意,我选择了偏移值,因此示例有效。您将不得不弄清楚如何将每个图像的偏移值转换为图中的一小部分。

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 http://i41.tinypic.com/33wnrqs.png

答案 1 :(得分:0)

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