ENH: add get_gridspec convenience method to subplots by jklymak · Pull Request #11438 · matplotlib/matplotlib · GitHub
Skip to content
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
20 changes: 20 additions & 0 deletions doc/users/next_whats_new/subplot_get_gridspec.rst
24 changes: 24 additions & 0 deletions examples/subplots_axes_and_figures/gridspec_and_subplots.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
"""
==================================================
Combining two subplots using subplots and GridSpec
==================================================

Sometimes we want to combine two subplots in an axes layout created with
`~.Figure.subplots`. We can get the `~.gridspec.GridSpec` from the axes
and then remove the covered axes and fill the gap with a new bigger axes.
Here we create a layout with the bottom two axes in the last column combined.

See: :doc:`/tutorials/intermediate/gridspec`
"""
import matplotlib.pyplot as plt

fig, axs = plt.subplots(ncols=3, nrows=3)
gs = axs[1, 2].get_gridspec()
# remove the underlying axes
for ax in axs[1:, -1]:
ax.remove()
axbig = fig.add_subplot(gs[1:, -1])
axbig.annotate('Big Axes \nGridSpec[1:, -1]', (0.1, 0.5),
xycoords='axes fraction', va='center')

fig.tight_layout()
4 changes: 4 additions & 0 deletions lib/matplotlib/axes/_subplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -117,6 +117,10 @@ def set_subplotspec(self, subplotspec):
"""set the SubplotSpec instance associated with the subplot"""
self._subplotspec = subplotspec

def get_gridspec(self):
"""get the GridSpec instance associated with the subplot"""
return self._subplotspec.get_gridspec()

def update_params(self):
"""update the subplot position from fig.subplotpars"""

Expand Down
6 changes: 6 additions & 0 deletions lib/matplotlib/tests/test_subplots.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,3 +143,9 @@ def test_subplots_offsettext():
axes[1, 0].plot(x, x)
axes[0, 1].plot(y, x)
axes[1, 1].plot(y, x)


def test_get_gridspec():
# ahem, pretty trivial, but...
fig, ax = plt.subplots()
assert ax.get_subplotspec().get_gridspec() == ax.get_gridspec()
16 changes: 16 additions & 0 deletions tutorials/intermediate/gridspec.py