Reading Time: 2 minutes

If your Matplotlib save plot outputs a blank plot, you can make it work through any of the two ways mentioned in this post.

Problem Cause:

You have used “plt.savefig()” after plt.show() or plt.close()

Problem Solution

You can use any one of below.

  1. Using the save plot command at the right spot – before plt.show()
  2. Using the figure returned by plt.subplots() to save the plot

Let us see an example to create such a problem which causes to output a blank figure in Matplotlib, and solve it.

Example

Demo code which contains mistake

Below code is creating a blank plot for me to explain this content. Go to Solution – 1 / Solution 2 for solutions.

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [4, 7, 5, 6, 3]
plt.bar(x, y)
plt.show()
plt.savefig("myfigure.png")

Using plt.savefig after plt.show is a mistake. Because, when plt.show is executed, it displays figure on the screen and closes the figure. This is why you get an empty plot when you save it after plt.show.

Solution – 1

The right spot to use plt.savefig command is before plt.show(). Below is the correct way.

x = [1, 2, 3, 4, 5]
y = [4, 7, 5, 6, 3]
plt.bar(x, y)
plt.title("Solution-1")
plt.savefig("myfigure2.png")
plt.show()

Solution – 2

You can use plt.subplots() command. It returns two values – one if the figure itself, and the other is axes. Use the figure returned by plt.subplots to save it at a convenient time. This method works even if the plot is saved after the plt.show() because we have saved the figure in the variable “fig”. Below is the correct usage.

x = [1, 2, 3, 4, 5]
y = [4, 7, 5, 6, 3]
fig, ax = plt.subplots()
ax.bar(x, y)
plt.title("Solution-2")
plt.show()
fig.savefig("myfigure3.png")

You can see my output screenshots below. First one is the saved blank plot. Next two are the saved output plots when I used Solution 1 and Solution 2.

Screenshot – Matplotlib save plot is saving a blank plot

Code used here is also available in my GitHub.

References

Matplotlib Documentation – matplotlib.pyplot.subplots

Similar Posts

Thanks for reading my post. If you find this helpful, please consider following me on Facebook / Twitter / Linkedin.

(Featured Image: Image by Kawita Chitprathak from Pixabay)

Source link

Spread the Word!