0

I know how to plot a single numpy array

import matplotlib.pyplot as plt
plt.imshow(np.array)

But is there any way to plot multiple numpy array in one figure? I know plt.subplots() can display multiple pictures. But it seems hard in my case. I have tried to use a for loop.

fig, ax = plt.subplots()
for i in range(10):
   ax.imshow(np.array)  # i_th numpy array

This seems to plot a single numpy array one by one. Is there any ways to plot all my 10 numpy arrays in one figure?

PS: Here each my 2d numpy array represents the pixel of a picture. plot seems to plot lines which is not suitable in my case.

2
  • It is unclear to me what you want to see as the end result. Do your 10 arrays have the same dimensions? If so: what is your desired result after plotting these 10 arrays 'together'? If you keep plotting the newest array will simply overlap the others. Commented Oct 10, 2020 at 15:20
  • @stfwn Yes, they are the same dimension. My desired result would be a three rows of figs. Number of figs in each row are 4,4,2 Commented Oct 10, 2020 at 15:26

1 Answer 1

1

The documentation for plt.subplots() (here) specifies that it takes an nrows and ncols arguments and returns a fig object and an array of ax objects. For your case this would look like this:

fig, axs = plt.subplots(3, 4)

axs now contains a 2D array filled with ax objects that you can use to plot various things, e.g. axs[0,1].plot([1,2],[3,4,]) would plot something on the first row, second column.

If you want to remove a particular ax object you can do that with .remove(), e.g. axs[0,1].remove().

For .imshow it works in exactly the same way as .plot: select the ax you want and call imshow on it.

A full example with simulated image data for your case would be:

import numpy as np
import matplotlib.pyplot as plt

fig, axs = plt.subplots(3, 4)
images = [np.array([[1,2],[3,4]]) for _ in range(10)]
for i, ax in enumerate(axs.flatten()):
    if i < len(images):
        ax.imshow(images[i])
    else:
        ax.remove()
plt.show()

With as the result:

enter image description here

Sign up to request clarification or add additional context in comments.

3 Comments

OP doesn't want to plot in different subplots. OP wants to overlay multiple arrays over the same figure
Sorry for this ignoring an important information. My numpy array here represents the pixel of a picture(shape of numpy array is 128*128). I have tried to use axs.plt, it plots lines. I think I still need to use plt.imshow to display the picture.
For imshow it works the same as it does for plot. I edited my answer to show a full example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.