Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between plt.subplots() and plt.figure()

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?

like image 323
Vedsar Kushwaha Avatar asked Apr 14 '15 04:04

Vedsar Kushwaha


1 Answers

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.

like image 181
ted930511 Avatar answered Nov 25 '22 12:11

ted930511