Open In App

How to Create an Empty Figure with Matplotlib in Python?

Creating a figure explicitly is an object-oriented style of interfacing with matplotlib. The figure is a basic building block of creating a plot as Matplotlib graphs our data on figures. This figure keeps track of all other components such as child axes, legends, title, axis, etc.

Steps to create an empty figure : 



For installing the ipympl run this command into your terminal:

For conda environment.



conda install ipympl -c conda-forge

For normal python terminal:

pip install ipympl

Below is the implementation:

Example1 :




# importing the library
import matplotlib
  
# Enabling interactive backend ipympl in
# jupyter notebook or you can use
# any other backend
%matplotlib ipympl
  
import matplotlib.pyplot as plt
  
# an empty figure with no axes
fig = plt.figure()  

Output:

Example 2 :

You can also use another interactive backend to display your figure like TkAgg( requires TkInter installed).




# using different backend
import matplotlib
%matplotlib tk
import matplotlib.pyplot as plt
  
#creating a figure
fig = plt.figure()

Output :

Figure2_gfg

Note: Displaying the figure in a different editor or python shell will need you to play with backends.

show() method also displays an empty figure but you have to save that figure before using show() command.

Example :

In the following example, I have used figsize attribute to change the size of the figure.




import matplotlib
  
# changing backend
%matplotlib tk
import matplotlib.pyplot as plt
  
# saving the figure
plt.savefig('testfigure.png',
            dpi = 100)
  
# displaying the figure
plt.show()

Output :

figure3_gfg


Article Tags :