简体   繁体   中英

Do I need a figure? What are they for?

I have begun using matplotlib and I am somewhat confused as to why figures exist. Sometimes I see code where a figure is declared and then a plot is made, and sometimes I see things like this:

import numpy as np
import matplotlib.pyplot as plt

data = np.loadtxt('initial.dat','float')
plt.plot(data[:,0], data[:,1])
plt.xlabel("x (Angstroms)")
plt.ylabel("V (eV)")
plt.savefig('v.png',bbox_inches='tight')
plt.clf()

I read the documentation on figure and plot, but I don't get it. Why do figures exist?

A figure will always exist once you create some plot with matplotlib.

The introductory matplotlib page may help here:

在此输入图像描述

The whole figure. The figure keeps track of all the child Axes, a smattering of 'special' artists (titles, figure legends, etc), and the canvas. (Don't worry too much about the canvas, it is crucial as it is the object that actually does the drawing to get you your plot, but as the user it is more-or-less invisible to you). A figure can have any number of Axes, but to be useful should have at least one.

You can imagine the figure to be the white sheet of paper you draw a plot on. A figure has some size, maybe a background and most importantly it is the container for everything you draw into it. In most cases this will be one or more axes. If there wasn't any figure, there wouldn't be any sheet of paper to draw your plot to (you cannot draw a line in the air).

Even if you haven't explicitely created the figure, it is automatically created in the background.

import matplotlib.pyplot as plt
plt.plot([1,2,3])
# at this point we already have a figure, because the plot needs to live somewhere
# we can get a handle to the figure via
figure = plt.gcf()

Examples of when you explicitely need a figure:

  • If you want to create a second figure.

     plt.plot([1,2,3]) plt.figure(2) plt.plot([2,4,6]) 
  • If you want to set the figure size or other figure parameters.

     plt.figure(figsize=(5,4), dpi=72) 
  • If you want to change the padding of the subplot(s).

     fig, ax=plt.subplots() fig.subplots_adjust(bottom=0.2) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM