[Matplotlib] When drawing multiple images, the content of the previous image overlaps the next image

Problem Description

When plotting multiple images with matplotlib, there may be an overlap in the result of two images (canvas overlap)

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [2, 1, 5, 3, 2]

plt.plot(x, y1)
plt.savefig("1.png")

plt.plot(x, y2)
plt.savefig("2.png")

The image saved this way is as follows:

  • 1.PNG
    insert image description here
  • 2. PNG
    insert image description here
    can be found that we want to save (x, y1) and (x, y2) as two images separately, but the result of two lines appears in the last saved image 2. PNG, if directly plt.show () is actually normal, this situation will only appear when saving the image.

Solution:

Every time an image is drawn, declare a new canvas: plt.figure()

import matplotlib.pyplot as plt

x = [1, 2, 3, 4, 5]
y1 = [1, 2, 3, 4, 5]
y2 = [2, 1, 5, 3, 2]

plt.figure()  # 声明一个新画布
plt.plot(x, y1)
plt.savefig("1.png")

plt.figure()  # 声明一个新画布
plt.plot(x, y2)
plt.savefig("2.png")

The image is as follows:

  • 1.PNG
    insert image description here
  • 2.PNG
    insert image description here

Guess you like

Origin blog.csdn.net/qq_41340996/article/details/120277399