10000 Rewrite subplots_demo · matplotlib/matplotlib@e5d5dcf · GitHub
[go: up one dir, main page]

Skip to content

Commit e5d5dcf

Browse files
committed
Rewrite subplots_demo
1 parent df10f3e commit e5d5dcf

File tree

1 file changed

+162
-73
lines changed

1 file changed

+162
-73
lines changed
Lines changed: 162 additions & 73 deletions
Original file line numberDiff line numberDiff line change
@@ -1,103 +1,192 @@
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

13+
# sphinx_gallery_thumbnail_number = 11
14+
1415
import matplotlib.pyplot as plt
1516
import numpy as np
1617

17-
# Simple data to display in various forms
18+
# Some example data to display
1819
x = np.linspace(0, 2 * np.pi, 400)
1920
y = np.sin(x ** 2)
2021

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

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

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)
51+
###############################################################################
52+
# If you are creating just a few Axes, it's handy to unpack them immediately to
53+
# dedicated variables for each Axes. That way, we can use ``ax1`` instead of
54+
# the more verbose ``axs[0]``.
55+
56+
fig, (ax1, ax2) = plt.subplots(2)
57+
fig.suptitle('Vertically stacked subplots')
58+
ax1.plot(x, y)
59+
ax2.plot(x, -y)
3760

3861
###############################################################################
39-
# Two subplots, unpack the axes array immediately
62+
# To obtain side-by-side subplots, pass parameters ``1, 2`` for one row and two
63+
# columns.
4064

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

4670
###############################################################################
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:
71+
# Stacking subplots in two directions
72+
# """""""""""""""""""""""""""""""""""
73+
#
74+
# When stacking in two directions, the returned `axs` is a 2D numpy array.
75+
#
76+
# If you have to set parameters for each subplot it's handy to iterate over
77+
# all subplots in a 2D grid using ``for ax in axs.flat:``.
78+
79+
fig, axs = plt.subplots(2, 2)
80+
axs[0, 0].plot(x, y)
81+
axs[0, 0].set_title('Axis [0,0]')
82+
axs[0, 1].plot(x, y, 'tab:orange')
83+
axs[0, 1].set_title('Axis [0,1]')
84+
axs[1, 0].plot(x, -y, 'tab:green')
85+
axs[1, 0].set_title('Axis [1,0]')
86+
axs[1, 1].plot(x, -y, 'tab:red')
87+
axs[1, 1].set_title('Axis [1,1]')
88+
89+
for ax in axs.flat:
90+
ax.set(xlabel='x-label', ylabel='y-label')
91+
92+
# Hide x labels and tick labels for top plots and y ticks for right plots.
93+
for ax in axs.flat:
5894
ax.label_outer()
5995

6096
###############################################################################
61-
# Row and column sharing
97+
# You can use tuple-unpacking also in 2D to assign all subplots to dedicated
98+
# variables:
6299

63-
f, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, sharex='col', sharey='row')
64-
f.suptitle('Sharing x per column, y per row')
100+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2)
101+
fig.suptitle('Sharing x per column, y per row')
65102
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')
103+
ax2.plot(x, y**2, 'tab:orange')
104+
ax3.plot(x, -y, 'tab:green')
105+
ax4.plot(x, -y**2, 'tab:red')
106+
107+
for ax in axs.flat:
108+
ax.label_outer()
69109

70110
###############################################################################
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:
111+
# Sharing axes
112+
# """"""""""""
113+
#
114+
# By default, each Axes is scaled individually. Thus, if the ranges are
115+
# different the tick values of the subplots do not align.
116+
117+
fig, (ax1, ax2) = plt.subplots(2)
118+
fig.suptitle('Axes values are scaled individually by default')
119+
ax1.plot(x, y)
120+
ax2.plot(x + 1, -y)
121+
122+
###############################################################################
123+
#
124+
# You can use *sharex* or *sharey* to align the horizontal or vertical axis.
125+
126+
fig, (ax1, ax2) = plt.subplots(2, sharex=True)
127+
fig.suptitle('Aligning x-axis using sharex')
128+
ax1.plot(x, y)
129+
ax2.plot(x + 1, -y)
130+
131+
###############################################################################
132+
# Setting *sharex* or *sharey* to ``True`` enables global sharing across the
133+
# whole grid, i.e. also the y-axes of vertically stacked subplots have the
134+
# same scale when using ``sharey=True``.
135+
136+
fig, axs = plt.subplots(3, sharex=True, sharey=True)
137+
fig.suptitle('Sharing both axes')
138+
axs[0].plot(x, y ** 2)
139+
axs[1].plot(x, 0.3 * y, 'o')
140+
axs[2].plot(x, y, '+')
141+
142+
###############################################################################
143+
# For subplots that are sharing axes one set of tick labels is enough. Tick
144+
# labels of inner Axes are automatically removed by *sharex* and *sharey*.
145+
# Still there remains an unused empty space between the subplots.
146+
#
147+
# The parameter *gridspec_kw* of `.pyplot.subplots` controls the grid
148+
# properties (see also `.GridSpec`). For example, we can reduce the height
149+
# between vertical subplots using ``gridspec_kw={'hspace': 0}``.
150+
#
151+
# `.label_outer` is a handy method to remove labels and ticks from subplots
152+
# that are not at the edge of the grid.
153+
154+
fig, axs = plt.subplots(3, sharex=True, sharey=True, gridspec_kw={'hspace': 0})
155+
fig.suptitle('Sharing both axes')
156+
axs[0].plot(x, y ** 2)
157+
axs[1].plot(x, 0.3 * y, 'o')
158+
axs[2].plot(x, y, '+')
159+
160+
# Hide x labels and tick labels for all but bottom plot.
161+
for ax in axs:
162+
ax.label_outer()
163+
164+
###############################################################################
165+
# Apart from ``True`` and ``False``, both *sharex* and *sharey* accept the
166+
# values 'row' and 'col' to share the values only per row or column.
167+
168+
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2,
169+
sharex='col', sharey='row',
170+
gridspec_kw={'hspace': 0,
171+
'wspace': 0})
172+
fig.suptitle('Sharing x per column, y per row')
173+
ax1.plot(x, y)
174+
ax2.plot(x, y**2, 'tab:orange')
175+
ax3.plot(x + 1, -y, 'tab:green')
176+
ax4.plot(x + 2, -y**2, 'tab:red')
177+
178+
for ax in axs:
86179
ax.label_outer()
87180

88181
###############################################################################
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()
182+
# Polar axes
183+
# """"""""""
184+
#
185+
# The parameter *subplot_kw* of `.pyplot.subplots` controls the subplot
186+
# properties (see also `.Figure.add_subplot`). In particular, this can be used
187+
# to create a grid of polar Axes.
188+
189+
fig, (ax1, ax2) = plt.subplots(1, 2, subplot_kw=dict(projection='polar'))
190+
ax1.plot(x, y)
191+
ax2.plot(x, y ** 2)
192+

0 commit comments

Comments
 (0)
0