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 or plt.close()

Problem Solution

You can use any one of below.

  1. Using the save plot command at the right spot – before
  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.


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], y)

Using plt.savefig after is a mistake. Because, when 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

Solution – 1

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

x = [1, 2, 3, 4, 5]
y = [4, 7, 5, 6, 3], y)

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 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(), y)

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.


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!