Reputation: 7248
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).
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()
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?
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?
Thanks
Upvotes: 3
Views: 4960
Reputation: 8704
You may want to consider the add_axes function of matplotlib.pyplot.
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()
which produces:
Upvotes: 4
Reputation: 26040
If I understand correctly, you seem to be looking for subplot
s. Have a look at the thumbnail gallery for examples.
Upvotes: 0