8000 Rewrite subplots_demo · matplotlib/matplotlib@07524e7 · GitHub
[go: up one dir, main page]

Skip to content

Commit 07524e7

Browse files
committed
Rewrite subplots_demo
1 parent df10f3e commit 07524e7

File tree

1 file changed

+157
-73
lines changed

1 file changed

+157
-73
lines changed
Lines changed: 157 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,187 @@
11
"""
2-
=============
3-
Subplots Demo
4-
=============
5-
6-
Examples illustrating the use of plt.subplots().
7-
8-
This function creates a figure and a grid of subplots with a single call, while
9-
providing reasonable control over how the individual plots are created. For
10-
very refined tuning of subplot creation, you can still use add_subplot()
11-
directly on a new figure.
2+
================================================
3+
Creating multiple subplots using ``plt.subplot``
4+
================================================
5+
6+
`.pyplot.subplots` creates a figure and a grid of subplots with a single call,
7+
while providing reasonable control over how the individual plots are created.
8+
For more advanced use cases you can use `.GridSpec` for a more general subplot
9+
layout or `.Figure.add_subplot` for adding subplots at arbitrary locations
10+
within the figure.
1211
"""
1312

1413
import matplotlib.pyplot as plt
1514
import numpy as np
1615

17-
# Simple data to display in various forms
16+
# Some example data to display
1817
x = np.linspace(0, 2 * np.pi, 400)
1918
y = np.sin(x ** 2)
2019

21-
plt.close('all')
22-
2320
###############################################################################
24-
# Just a figure and one subplot
25-
26-
f, ax = plt.subplots()
21+
# A figure with just one subplot
22+
# """"""""""""""""""""""""""""""
23+
#
24+
# ``subplots()`` without arguments returns a `.Figure` and a single
25+
# `~.axes.Axes`.
26+
#
27+
# This is actually the simplest and recommended way of creating a single
28+
# Figure and Axes.
29+
30+
fig, ax = plt.subplots()
2731
ax.plot(x, y)
28-
ax.set_title('Simple plot')
32+
ax.set_title('A single plot')
2933

3034
###############################################################################
31-
# Two subplots, the axes array is 1-d
35+
# Stacking subplots in one direction
36+
# """"""""""""""""""""""""""""""""""
37+
#
38+
# The first two optional arguments of `.pyplot.subplots` define the number of
39+
# rows and columns of the subplot grid.
40+
#
41+
# When stacking in one direction only, the returned `axs` is a 1D numpy array
42+
# containing the list of created Axes.
43+
44+
fig, axs = plt.subplots(2)
45+
fig.suptitle('Vertically stacked subplots')
46+
axs[0].plot(x, y)
47+
axs[1].plot(x, -y)
3248

33-
f, axarr = plt.subplots(2, sharex=True)
34-
f.suptitle('Sharing X axis')
35-
axarr[0].plot(x, y)
36-
axarr[1].scatter(x, y)
49+
###############################################################################
50+
# If you are creating just a few Axes, it's handy to unpack them immediately to
51+
# dedicated variables for each Axes. That way, we can use ``ax1`` instead of
52+
# the more verbose ``axs[0]``.
53+
54+
fig, (ax1, ax2) = plt.subplots(2)
55+
fig.suptitle('Vertically stacked subplots')
56+
ax1.plot(x, y)
57+
ax2.plot(x, -y)
3758

3859
###############################################################################
39-
# Two subplots, unpack the axes array immediately
60+
# To obtain side-by-side subplots, pass parameters ``1, 2`` for one row and two
61+
# columns.
4062

41-
f, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
42-
f.suptitle('Sharing Y axis')
63+
fig, (ax1, ax2) = plt.subplots(1, 2)
64+
fig.suptitle('Horizontally stacked subplots')
4365
ax1.plot(x, y)
44-
ax2.scatter(x, y)
66+
ax2.plot(x, -y)
4567

4668
###############################################################################
47-
# Three subplots sharing both x/y axes
48-
49-
f, axarr = plt.subplots(3, sharex=True, sharey=True)
50-
f.suptitle('Sharing both axes')
51-
axarr[0].plot(x, y)
52-
axarr[1].scatter(x, y)
53-
axarr[2].scatter(x, 2 * y ** 2 - 1, color='r')
54-
# Bring subplots close to each other.
55-
f.subplots_adjust(hspace=0)
56-
# Hide x labels and tick labels for all but bottom plot.
57-
for ax in axarr:
69+
# Stacking subplots in two directions
70+
# """""""""""""""""""""""""""""""""""
71+
#
72+
# When stacking in two directions, the returned `axs` is a 2D numpy array.
73+
#
74+
# If you have to set parameters for each subplot it's handy to iterate over
75+
# all subplots in a 2D grid using ``for ax in axs.flat:``.
76+
77+
fig, axs = plt.subplots(2, 2)
78+
axs[0, 0].plot(x, y)
79+
axs[0, 0].set_title('Axis [0,0]')
80+
axs[0, 1].plot(x, y, 'tab:orange')
81+
axs[0, 1].set_title('Axis [0,1]')
82+
axs[1, 0].plot(x, -y, 'tab:green')
83+
axs[1, 0].set_title('Axis [1,0]')
84+
axs[1, 1].plot(x, -y, 'tab:red')
85+
axs[1, 1].set_title('Axis [1,1]')
86+
87+
for ax in axs.flat:
88+
ax.set(xlabel='x-label', ylabel='y-label')
89+
90+
# Hide x labels and tick labels for top plots and y ticks for right plots.
91+
for ax in axs.flat:
5892
ax.label_outer()
5993

6094
###############################################################################
61-
# Row and column sharing
95+
# You can use tuple-unpacking also in 2D to assign all subplots to dedicated
96+
# variables:
6297

63-
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
64-
f.suptitle('Sharing x per column, y per row')
98+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
99+
fig.suptitle('Sharing x per column, y per row')
65100
ax1.plot(x, y)
66-
ax2.scatter(x, y)
67-
ax3.scatter(x, 2 * y ** 2 - 1, color='r')
68-
ax4.plot(x, 2 * y ** 2 - 1, color='r')
101+
ax2.plot(x, y**2, 'tab:orange')
102+
ax3.plot(x, -y, 'tab:green')
103+
ax4.plot(x, -y**2, 'tab:red')
69104

70105
###############################################################################
71-
# Four axes, returned as a 2-d array
72-
73-
f, axarr = plt.subplots(2, 2)
74-
axarr[0, 0].plot(x, y)
75-
axarr[0, 0].set_title('Axis [0,0]')
76-
axarr[0, 1].scatter(x, y)
77-
axarr[0, 1].set_title('Axis [0,1]')
78-
axarr[1, 0].plot(x, y ** 2)
79-
axarr[1, 0].set_title('Axis [1,0]')
80-
axarr[1, 1].scatter(x, y ** 2)
81-
axarr[1, 1].set_title('Axis [1,1]')
82-
for ax in axarr.flat:
83-
ax.set(xlabel='x-label', ylabel='y-label')
84-
# Hide x labels and tick labels for top plots and y ticks for right plots.
85-
for ax in axarr.flat:
106+
# Sharing axes
107+
# """"""""""""
108+
#
109+
# By default, each Axes is scaled individually. Thus, if the ranges are
110+
# different the tick values of the subplots do not align.
111+
112+
fig, (ax1, ax2) = plt.subplots(2)
113+
fig.suptitle('Axes values are scaled individually by default')
114+
ax1.plot(x, y)
115+
ax2.plot(x + 1, -y)
116+
117+
###############################################################################
118+
#
119+
# You can use *sharex* or *sharey* to align the horizontal or vertical axis.
120+
121+
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
122+
fig.suptitle('Aligning x-axis using sharex')
123+
ax1.plot(x, y)
124+
ax2.plot(x + 1, -y)
125+
126+
###############################################################################
127+
# Setting *sharex* or *sharey* to ``True`` enables global sharing across the
128+
# whole grid, i.e. also the y-axes of vertically stacked subplots have the
129+
# same scale when using ``sharey=True``.
130+
131+
fig, axs = plt.subplots(3, sharex=True, sharey=True)
132+
fig.suptitle('Sharing both axes')
133+
axs[0].plot(x, y ** 2)
134+
axs[1].plot(x, 0.3 * y, 'o')
135+
axs[2].plot(x, y, '+')
136+
137+
###############################################################################
138+
# For subplots that are sharing axes one set of tick labels is enough. Tick
139+
# labels of inner Axes are automatically removed by *sharex* and *sharey*.
140+
# Still there remains an unused empty space between the subplots.
141+
#
142+
# The parameter *gridspec_kw* of `.pyplot.subplots` controls the grid
143+
# properties (see also `.GridSpec`). For example, we can reduce the height
144+
# between vertical subplots using ``gridspec_kw={'hspace': 0}``.
145+
#
146+
# `.label_outer` is a handy method to remove labels and ticks from subplots
147+
# that are not at the edge of the grid.
148+
149+
fig, axs = plt.subplots(3, sharex=True, sharey=True, gridspec_kw={'hspace': 0})
150+
fig.suptitle('Sharing both axes')
151+
axs[0].plot(x, y ** 2)
152+
axs[1].plot(x, 0.3 * y, 'o')
153+
axs[2].plot(x, y, '+')
154+
155+
# Hide x labels and tick labels for all but bottom plot.
156+
for ax in axs:
157+
ax.label_outer()
158+
159+
###############################################################################
160+
# Apart from ``True`` and ``False``, both *sharex* and *sharey* accept the
161+
# values 'row' and 'col' to share the values only per row or column.
162+
163+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,
164+
sharex='col', sharey='row',
165+
gridspec_kw={'hspace': 0,
166+
'wspace': 0})
167+
fig.suptitle('Sharing x per column, y per row')
168+
ax1.plot(x, y)
169+
ax2.plot(x, y**2, 'tab:orange')
170+
ax3.plot(x + 1, -y, 'tab:green')
171+
ax4.plot(x + 2, -y**2, 'tab:red')
172+
173+
for ax in axs:
86174
ax.label_outer()
87175

88176
###############################################################################
89-
# Four polar axes
90-
91-
f, axarr = plt.subplots(2, 2, subplot_kw=dict(projection='polar'))
92-
axarr[0, 0].plot(x, y)
93-
axarr[0, 0].set_title('Axis [0,0]')
94-
axarr[0, 1].scatter(x, y)
95-
axarr[0, 1].set_title('Axis [0,1]')
96-
axarr[1, 0].plot(x, y ** 2)
97-
axarr[1, 0].set_title('Axis [1,0]')
98-
axarr[1, 1].scatter(x, y ** 2)
99-
axarr[1, 1].set_title('Axis [1,1]')
100-
# Fine-tune figure; make subplots farther from each other.
101-
f.subplots_adjust(hspace=0.3)
102-
103-
plt.show()
177+
# Polar axes
178+
# """"""""""
179+
#
180+
# The parameter *subplot_kw* of `.pyplot.subplots` controls the subplot
181+
# properties (see also `.Figure.add_subplot`). In particular, this can be used
182+
# to create a grid of polar Axes.
183+
184+
fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
185+
ax1.plot(x, y)
186+
ax2.plot(x, y ** 2)
187+

0 commit comments

Comments
 (0)
0