Skip to content

ENH: Subfigures #18356

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Oct 9, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 2 additions & 23 deletions doc/api/figure_api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,26 +5,5 @@
.. currentmodule:: matplotlib.figure

.. automodule:: matplotlib.figure
:no-members:
:no-inherited-members:

Classes
-------

.. autosummary::
:toctree: _as_gen/
:template: autosummary.rst
:nosignatures:

Figure
SubplotParams

Functions
---------

.. autosummary::
:toctree: _as_gen/
:template: autosummary.rst
:nosignatures:

figaspect
:members:
:inherited-members:
17 changes: 17 additions & 0 deletions doc/api/next_api_changes/development/18356-JMK.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
FigureBase class added, and Figure class made a child
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The new subfigure feature motivated some re-organization of the
`.figure.Figure` class, so that the new `.figure.SubFigure` class could have
all the capabilities of a figure.

The `.figure.Figure` class is now a subclass of `.figure.FigureBase`, where
`.figure.FigureBase` contains figure-level artist addition routines, and
the `.figure.Figure` subclass just contains features that are unique to the
outer figure.

Note that there is a new *transSubfigure* transform
associated with the subfigure. This transform also exists for a
`.Figure` instance, and is equal to *transFigure* in that case,
so code that uses the transform stack that wants to place objects on either
the parent figure or one of the subfigures should use *transSubfigure*.
53 changes: 53 additions & 0 deletions doc/users/next_whats_new/subfigures.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
New subfigure functionality
---------------------------
New `.figure.Figure.add_subfigure` and `.figure.Figure.subfigures`
functionalities allow creating virtual figures within figures. Similar
nesting was previously done with nested gridspecs
( see :doc:`/gallery/subplots_axes_and_figures/gridspec_nested`). However, this
did not allow localized figure artists (i.e. a colorbar or suptitle) that
only pertained to each subgridspec.

The new methods `.figure.Figure.add_subfigure` and `.figure.Figure.subfigures`
are meant to rhyme with `.figure.Figure.add_subplot` and
`.figure.Figure.subplots` and have most of the same arguments.

See :doc:`/gallery/subplots_axes_and_figures/subfigures`.

.. note::

The subfigure functionality is experimental API as of v3.4.

.. plot::

def example_plot(ax, fontsize=12, hide_labels=False):
pc = ax.pcolormesh(np.random.randn(30, 30))
if not hide_labels:
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
return pc

np.random.seed(19680808)
fig = plt.figure(constrained_layout=True, figsize=(10, 4))
subfigs = fig.subfigures(1, 2, wspace=0.07)

axsLeft = subfigs[0].subplots(1, 2, sharey=True)
subfigs[0].set_facecolor('0.75')
for ax in axsLeft:
pc = example_plot(ax)
subfigs[0].suptitle('Left plots', fontsize='x-large')
subfigs[0].colorbar(pc, shrink=0.6, ax=axsLeft, location='bottom')

axsRight = subfigs[1].subplots(3, 1, sharex=True)
for nn, ax in enumerate(axsRight):
pc = example_plot(ax, hide_labels=True)
if nn == 2:
ax.set_xlabel('xlabel')
if nn == 1:
ax.set_ylabel('ylabel')
subfigs[1].colorbar(pc, shrink=0.6, ax=axsRight)
subfigs[1].suptitle('Right plots', fontsize='x-large')

fig.suptitle('Figure suptitle', fontsize='xx-large')

plt.show()
4 changes: 4 additions & 0 deletions examples/subplots_axes_and_figures/gridspec_nested.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,10 @@
GridSpecs can be nested, so that a subplot from a parent GridSpec can
set the position for a nested grid of subplots.

Note that the same functionality can be achieved more directly with
`~.figure.FigureBase.subfigures`; see
:doc:`/gallery/subplots_axes_and_figures/subfigures`.

"""
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
Expand Down
148 changes: 148 additions & 0 deletions examples/subplots_axes_and_figures/subfigures.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
"""
=================
Figure subfigures
=================

Sometimes it is desirable to have a figure with two different layouts in it.
This can be achieved with
:doc:`nested gridspecs</gallery/subplots_axes_and_figures/gridspec_nested>`,
but having a virtual figure with its own artists is helpful, so
Matplotlib also has "subfigures", accessed by calling
`matplotlib.figure.Figure.add_subfigure` in a way that is analagous to
`matplotlib.figure.Figure.add_subplot`, or
`matplotlib.figure.Figure.subfigures` to make an array of subfigures. Note
that subfigures can also have their own child subfigures.

.. note::
``subfigure`` is new in v3.4, and the API is still provisional.

"""
import matplotlib.pyplot as plt
import numpy as np


def example_plot(ax, fontsize=12, hide_labels=False):
pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2.5, vmax=2.5)
if not hide_labels:
ax.set_xlabel('x-label', fontsize=fontsize)
ax.set_ylabel('y-label', fontsize=fontsize)
ax.set_title('Title', fontsize=fontsize)
return pc

np.random.seed(19680808)
# gridspec inside gridspec
fig = plt.figure(constrained_layout=True, figsize=(10, 4))
subfigs = fig.subfigures(1, 2, wspace=0.07)

axsLeft = subfigs[0].subplots(1, 2, sharey=True)
subfigs[0].set_facecolor('0.75')
for ax in axsLeft:
pc = example_plot(ax)
subfigs[0].suptitle('Left plots', fontsize='x-large')
subfigs[0].colorbar(pc, shrink=0.6, ax=axsLeft, location='bottom')

axsRight = subfigs[1].subplots(3, 1, sharex=True)
for nn, ax in enumerate(axsRight):
pc = example_plot(ax, hide_labels=True)
if nn == 2:
ax.set_xlabel('xlabel')
if nn == 1:
ax.set_ylabel('ylabel')

subfigs[1].set_facecolor('0.85')
subfigs[1].colorbar(pc, shrink=0.6, ax=axsRight)
subfigs[1].suptitle('Right plots', fontsize='x-large')

fig.suptitle('Figure suptitle', fontsize='xx-large')

plt.show()

##############################################################################
# It is possible to mix subplots and subfigures using
# `matplotlib.figure.Figure.add_subfigure`. This requires getting
# the gridspec that the subplots are laid out on.

fig, axs = plt.subplots(2, 3, constrained_layout=True, figsize=(10, 4))
gridspec = axs[0, 0].get_subplotspec().get_gridspec()

# clear the left column for the subfigure:
for a in axs[:, 0]:
a.remove()

# plot data in remaining axes:
for a in axs[:, 1:].flat:
a.plot(np.arange(10))

# make the subfigure in the empy gridspec slots:
subfig = fig.add_subfigure(gridspec[:, 0])

axsLeft = subfig.subplots(1, 2, sharey=True)
subfig.set_facecolor('0.75')
for ax in axsLeft:
pc = example_plot(ax)
subfig.suptitle('Left plots', fontsize='x-large')
subfig.colorbar(pc, shrink=0.6, ax=axsLeft, location='bottom')

fig.suptitle('Figure suptitle', fontsize='xx-large')
plt.show()

##############################################################################
# Subfigures can have different widths and heights. This is exactly the
# same example as the first example, but *width_ratios* has been changed:

fig = plt.figure(constrained_layout=True, figsize=(10, 4))
subfigs = fig.subfigures(1, 2, wspace=0.07, width_ratios=[2, 1])

axsLeft = subfigs[0].subplots(1, 2, sharey=True)
subfigs[0].set_facecolor('0.75')
for ax in axsLeft:
pc = example_plot(ax)
subfigs[0].suptitle('Left plots', fontsize='x-large')
subfigs[0].colorbar(pc, shrink=0.6, ax=axsLeft, location='bottom')

axsRight = subfigs[1].subplots(3, 1, sharex=True)
for nn, ax in enumerate(axsRight):
pc = example_plot(ax, hide_labels=True)
if nn == 2:
ax.set_xlabel('xlabel')
if nn == 1:
ax.set_ylabel('ylabel')

subfigs[1].set_facecolor('0.85')
subfigs[1].colorbar(pc, shrink=0.6, ax=axsRight)
subfigs[1].suptitle('Right plots', fontsize='x-large')

fig.suptitle('Figure suptitle', fontsize='xx-large')

plt.show()

##############################################################################
# Subfigures can be also be nested:

fig = plt.figure(constrained_layout=True, figsize=(10, 8))

fig.suptitle('fig')

subfigs = fig.subfigures(1, 2, wspace=0.07)

subfigs[0].set_facecolor('coral')
subfigs[0].suptitle('subfigs[0]')

subfigs[1].set_facecolor('coral')
subfigs[1].suptitle('subfigs[1]')

subfigsnest = subfigs[0].subfigures(2, 1, height_ratios=[1, 1.4])
subfigsnest[0].suptitle('subfigsnest[0]')
subfigsnest[0].set_facecolor('r')
axsnest0 = subfigsnest[0].subplots(1, 2, sharey=True)
for nn, ax in enumerate(axsnest0):
pc = example_plot(ax, hide_labels=True)
subfigsnest[0].colorbar(pc, ax=axsnest0)

subfigsnest[1].suptitle('subfigsnest[1]')
subfigsnest[1].set_facecolor('g')
axsnest1 = subfigsnest[1].subplots(3, 1, sharex=True)

axsRight = subfigs[1].subplots(2, 2)

plt.show()
2 changes: 1 addition & 1 deletion examples/subplots_axes_and_figures/subplots_demo.py
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@
# Still there remains an unused empty space between the subplots.
#
# To precisely control the positioning of the subplots, one can explicitly
# create a `.GridSpec` with `.add_gridspec`, and then call its
# create a `.GridSpec` with `.Figure.add_gridspec`, and then call its
# `~.GridSpecBase.subplots` method. For example, we can reduce the height
# between vertical subplots using ``add_gridspec(hspace=0)``.
#
Expand Down
Loading