14

In python matplotlib, there are two convention used to draw plots:

 1. 

plt.figure(1,figsize=(400,8))

 2. 

fig,ax = plt.subplots()
fig.set_size_inches(400,8)

Both have different ways of doing the same thing. eg defining axis label.

Which one is better to use? What is the advantage of one over the other? Or what is the "Good Practice" for plotting a graph using matplotlib?

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76
Vedsar Kushwaha
  • 313
  • 2
  • 11
  • 5
    `plt.figure` just creates a figure (but with no axes in it) `plt.subplots` takes optional arguments (ex `plt.subplots(2, 2)`) to create an array of axes in the figure. Most (all?) of the kwargs that `plt.figure` takes `plt.subplots` also takes. – tacaswell Apr 14 '15 at 04:39
  • 1
    also good to know: matplotlib plots into (onto) axes, so the most explicit code usually says something like `ax1.plot(...)`. But `pyplot` does the thing most-likely to be helpful at the interpreter, so if you've only defined a Figure (as in the first example) and call `plt.plot(...)` , pyplot will *generate* an axes on the current Figure and plot into that. – cphlewis Apr 14 '15 at 17:11

1 Answers1

3

Although @tacaswell already gave a brief comment on the key difference. I will add more to this question only from my own experience with matplotlib.

plt.figure just creates a Figure (but with no Axes in it), this means you have to specify the ax to place your data (lines, scatter points, images). Minimum code should look like this:

import numpy as np
import matplotlib.pyplot as plt

# create a figure
fig = plt.figure(figsize=(7.2, 7.2))
# generate ax1
ax1 = fig.add_axes([0.1, 0.1, 0.5, 0.5])
# generate ax2, make it red to distinguish
ax2 = fig.add_axes([0.6, 0.6, 0.3, 0.3], fc='red')
# add data
x = np.linspace(0, 2*np.pi, 20)
y = np.sin(x)
ax1.plot(x, y)
ax2.scatter(x, y)

In the case of plt.subplots(nrows=, ncols=), you will get Figure and an array of Axes(AxesSubplot). It is mostly used for generating many subplots at the same time. Some example code:

def display_axes(axes):
    for i, ax in enumerate(axes.ravel()):
        ax.text(0.5, 0.5, s='ax{}'.format(i+1), transform=ax.transAxes)

# create figures and (2x2) axes array
fig, axes = plt.subplots(2, 2, figsize=(7.2, 7.2))
# four (2*2=4) axes
ax1, ax2, ax3, ax4 = axes.ravel()
# for illustration purpose
display_axes(axes)

Summary:

  • plt.figure() is usually used when you want more customization to you axes, such as positions, sizes, colors and etc. You can see artist tutorial for more details. (I personally prefer this for individual plot).

  • plt.subplots() is recommended for generating multiple subplots in grids. You can also achieve higher flexibility using 'gridspec' and 'subplots', see details here.

Jiadong
  • 1,822
  • 1
  • 17
  • 37