Reading Time: 2 minutes


In this article, you will learn how to save a plot and don’t show in Matplotlib jupyter notebook screen.

Generally for creating and showing the plot, we use commands like:

  • plt.plot()
  • plt.savefig()
  • plt.close()

If you want to NOT show the plot in jupyter notebook, the sequence of steps should be similar to:

  • plt.plot()
  • plt.savefig()
  • plt.close()

Note that I have skipped command. This makes the figure to not appear in jupyter notebook while you run the code.

To save the plot

Please refer this article: How to save a plot in Matplotlib?

You can understand what are the supported formats to save a plot, and how to save them with examples.

Don’t show the plot

The command “” also written as “” is the command responsible for showing the plot. If you want the figure to NOT show, then simply skip this step.

By this way, the plot is generated, saved and closed. And, not shown in the jupyter notebook.

Example – Don’t show plot in Matplotlib

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [4, 6, 3, 7, 2]
plt.plot(x, y)
plt.xlabel("x values")
plt.ylabel("y values")
plt.title("Matplotlib - Save plot but dont show")

You can’t see the figure when you run the code. But, “filename.png” plot is saved in the same folder where this code is present. Look at the below screenshot showing this code and the generated plot circled in green. (This folder contains some other files too which is not relevant here. Please ignore.)

Matplotlib - save plot but dont show - screenshot
Matplotlib – save plot but dont show – screenshot

If you want to save in a different location, specify the full path in plt.savefig() instead of just the file name, as shown below.


A copy of the code given here is available in my GitHub.


Matplotlib documentation – matplotlib.pyplot.close

Further Reading

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

(Image by Bruno /Germany from Pixabay)


Source link

Spread the Word!