Overlay plot on an image inside a for loop Python

Question:

I am trying to overlay a matplotlib plot on an image using the following code snippet.

plt.imshow(image, zorder=0)
plt.plot(some_array, zorder=1)
plt.savefig('image_array.png')

If I now include this code inside a for loop to overlay a plot on a different image in each loop, the resulting images overlap. For example, image_array2.png sits on top of image_array1.png and so on. How do I correctly save the figures without overlapping?

Asked By: Nanda

||

Answers:

for i in range(number_of_images):
    plt.imshow(image[i], zorder=0)
    plt.plot(some_array[i], zorder=1)
    plt.savefig('image_array' + str(i) + '.png')
    plt.clf()

If you’re trying to save multiple plots on different images using a for loop, the plots end up overlapping. But don’t worry, there’s a way to fix it. You can add a line of code, called ‘plt.clf()’, before creating the next plot. This line of code clears the current figure, so the next plot you create doesn’t overlap with the previous one.

fig, ax = plt.subplots(1, number_of_images)
for i in range(number_of_images):
    ax[i].imshow(image[i], zorder=0)
    ax[i].plot(some_array[i], zorder=1)
plt.savefig('image_array.png')

You can also use matplot subplot method.

Answered By: Suren

You can add plt.clf() after plt.savefig() to clear the current figure before the next iteration of the loop.
This will ensure that the previous figure is cleared before the next one is plotted, preventing overlaps. Alternatively, you could also create a new figure at the beginning of each iteration using the plt.figure(), which would also clear any previous figures:

plt.figure()
plt.imshow(image, zorder=0)
plt.plot(some_array, zorder=1)
plt.savefig('image_array.png')

Answered By: Lahcen YAMOUN
import matplotlib.pyplot as plt
import numpy as np

# load image
img = plt.imread("image.jpg")

# loop through your data
for i in range(5):
    x = np.random.rand(10)
    y = np.random.rand(10)

    # create a new figure
    plt.figure()
    plt.imshow(img)
    plt.axis('off')
    # plot the data on top of the image
    plt.plot(x, y, 'o-', color='r')
    plt.title('Plot {}'.format(i))
    plt.show()
Answered By: brahim Elmouden
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.