Saturday, November 16, 2024
Google search engine
HomeLanguagesHow to Create an Empty Figure with Matplotlib in Python?

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 : 

  • First, we import the matplotlib library specifically the pyplot module of matplotlib.
  • Then we create a figure object using plt.figure() and keep a reference to that by setting it equal to the ‘fig’ variable. This figure object is empty as we have not added any figure components such as axis, legend, axis, etc.
  • We are using jupyter notebook, and we have to change out backend to ipympl(interactive backend) as with the default backend it was showing a Non-Gui backend error.

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 :

Python3




# 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).

Python3




# 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.

Python3




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

RELATED ARTICLES

Most Popular

Recent Comments