Explain Codes LogoExplain Codes Logo

Why do many examples use fig, ax = plt.subplots()

python
matplotlib
plotting
data-visualization
Alex KataevbyAlex KataevΒ·Sep 5, 2024
⚑TLDR

The pattern fig, ax = plt.subplots() is a compact method to create a matplotlib plot. In a single step, it initializes both the figure instance (fig) which is the box within which plot is drawn, and the axes (ax) where data is plotted. This method eases and quickens the plot customization process, saving you from handling separate figure and axes creation commands.

Let's see its simplicity and effectiveness in a Python code snippet:

import matplotlib.pyplot as plt # Creating the 'box' and the 'plotting area' together, like a 2-for-1 deal fig, ax = plt.subplots() # And our 'plotting area' is ready to host the data party ax.plot([1, 2, 3], [4, 5, 6]) # Here comes the data parade... πŸ₯³ # Finally, let's reveal our magnificent plot plt.show()

This method efficiently presents you directly with the Axes object, which lies at the heart of all the plotting actions.

Going deeper: unpacking fig, ax

The concise fig, ax = plt.subplots() provides an extensive level of customization and control. Here's why it's common in professional code:

Hitting the canvas: Explore fig

  • Saving plots: Harness fig.savefig('plot.png') to save the 'Mona Lisa' of data visualizations.
  • Adjusting size: Use fig.set_size_inches(10, 8) to make your plot canvas as big as Lady Liberty.
  • Complex layouts: fig.tight_layout() helps fits your subplots just right, like Cinderella's glass slipper.

Building the plot: Master ax

  • Advanced plots: Easily switch between simple to complex plots such as ax.bar(), ax.pie().
  • Refining aesthetics: ax.set(xlabel='X', ylabel='Y', title='Title') is like an aesthetician for your plot.
  • Working with subplots: Enjoy creating multiple axes in a neat grid layout through fig, axs = plt.subplots(2, 2) - it's like an apartment for your plots!

Central control: Modify subplot grid

  • Shared X or Y axes: Turn on sharex=True or sharey=True to compare plots directly - it's like having your plots on a twin telepathic link!
  • Flexible grids: Use the gridspec_kw parameter to customize subplot dimensions. So your subplots aren't always stuck in a rigid grid!
  • Intra-plot references: Axes can reference one another for linked behaviours or annotations. Just like how siblings fight over the TV remote! πŸ˜†

Understanding practical applications

Comprehensive usage

Working with fig, ax offers a Pantheon of full-feature access, making every single feature in matplotlib's arsenal readily available for you.

Streamlined refactoring

Code refactoring never felt so good! Simply reuse and manipulate the axes objects to create your desired plots, especially helpful in large code bases, where plots are created within various functions.

Quick adjustments with plt.gca()

The trusty plt.gca() works wonders when operating in a context where axes are implied. This function retrieves the current axes efficiently which is quite handy for quick modifications or when building atop existing plots.