一个matplotlib图中的多个图 [英] Multiple plots in a single matplotlib figure

查看:88
本文介绍了一个matplotlib图中的多个图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In a Python script, I have a set of 2D NumPy float arrays, let say n1, n2, n3 and n4. For each such array I have two integer values offset_i_x and offset_i_y (replace i by 1, 2, 3 and 4).

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

Currently I'm able to create an image for one NumPy array using the following script:

   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还是很陌生.我该怎么办?

Now I would like to consider each array to be a tile of a bigger image and should be placed according to the offset_i_x/y values, to finally write a single figure instead of 4 (in my example). I'm very new to MatplotLib and Python in general. How can I do that?

我还注意到,无论原始NumPy数组的大小如何,上面的脚本生成的图像均为480x480像素.如何控制生成的图像的大小?

Also I have noticed that the script above produces images that are 480x480 pixels, whatever the size of the original NumPy array. How can I control the size of the resulting image?

谢谢

推荐答案

您可能需要考虑 add_axes 函数.

以下是一个肮脏的示例,根据您想要实现的目标而定. 请注意,我选择了offsets的值,因此该示例可以正常工作.您将必须弄清楚如何将每个图像的偏移量值转换为数字的一部分.

Below is a dirty example, based on what you want to achieve. Note that I have chosen values of offsets so the example works. You will have to figure out how to convert the values of the offsets you have for each images in fraction of the figure.

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()

产生:

这篇关于一个matplotlib图中的多个图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆