0

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?

3 Answers 3

4
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.

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

1 Comment

Many thanks! plt.clf() resolved the issue.
1

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

Comments

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

Comments

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.