Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 90f6a35

Browse files
authored
Merge pull request #13775 from ImportanceOfBeingErnest/doc-scatter-hist-example
DOC: Scatter Hist example update
2 parents b3fadcb + 104cd8f commit 90f6a35

File tree

4 files changed

+169
-64
lines changed

4 files changed

+169
-64
lines changed

.flake8

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@ per-file-ignores =
7171

7272
examples/animation/frame_grabbing_sgskip.py: E402
7373
examples/axes_grid1/inset_locator_demo.py: E402
74+
examples/axes_grid1/scatter_hist_locatable_axes.py: E401, E402
7475
examples/axisartist/demo_curvelinear_grid.py: E402
7576
examples/color/color_by_yvalue.py: E402
7677
examples/color/color_cycle_default.py: E402
@@ -128,6 +129,7 @@ per-file-ignores =
128129
examples/lines_bars_and_markers/filled_step.py: E402
129130
examples/lines_bars_and_markers/horizontal_barchart_distribution.py: E402
130131
examples/lines_bars_and_markers/joinstyle.py: E402
132+
examples/lines_bars_and_markers/scatter_hist.py: E402
131133
examples/lines_bars_and_markers/scatter_piecharts.py: E402
132134
examples/lines_bars_and_markers/scatter_with_legend.py: E402
133135
examples/lines_bars_and_markers/span_regions.py: E402
Lines changed: 46 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,80 @@
11
"""
2-
============
3-
Scatter Hist
4-
============
2+
==================================
3+
Scatter Histogram (Locatable Axes)
4+
==================================
55
6+
Show the marginal distributions of a scatter as histograms at the sides of
7+
the plot.
8+
9+
For a nice alignment of the main axes with the marginals, the axes positions
10+
are defined by a ``Divider``, produced via `.make_axes_locatable`.
11+
12+
An alternative method to produce a similar figure is shown in the
13+
:doc:`/gallery/lines_bars_and_markers/scatter_hist` example. The advantage of
14+
the locatable axes method shown below is that the marginal axes follow the
15+
fixed aspect ratio of the main axes.
616
"""
17+
718
import numpy as np
819
import matplotlib.pyplot as plt
920
from mpl_toolkits.axes_grid1 import make_axes_locatable
1021

1122
# Fixing random state for reproducibility
1223
np.random.seed(19680801)
1324

14-
1525
# the random data
1626
x = np.random.randn(1000)
1727
y = np.random.randn(1000)
1828

1929

20-
fig, axScatter = plt.subplots(figsize=(5.5, 5.5))
30+
fig, ax = plt.subplots(figsize=(5.5, 5.5))
2131

2232
# the scatter plot:
23-
axScatter.scatter(x, y)
24-
axScatter.set_aspect(1.)
33+
ax.scatter(x, y)
34+
35+
# Set aspect of the main axes.
36+
ax.set_aspect(1.)
2537

2638
# create new axes on the right and on the top of the current axes
27-
# The first argument of the new_vertical(new_horizontal) method is
28-
# the height (width) of the axes to be created in inches.
29-
divider = make_axes_locatable(axScatter)
30-
axHistx = divider.append_axes("top", 1.2, pad=0.1, sharex=axScatter)
31-
axHisty = divider.append_axes("right", 1.2, pad=0.1, sharey=axScatter)
39+
divider = make_axes_locatable(ax)
40+
# below height and pad are in inches
41+
ax_histx = divider.append_axes("top", 1.2, pad=0.1, sharex=ax)
42+
ax_histy = divider.append_axes("right", 1.2, pad=0.1, sharey=ax)
3243

3344
# make some labels invisible
34-
axHistx.xaxis.set_tick_params(labelbottom=False)
35-
axHisty.yaxis.set_tick_params(labelleft=False)
45+
ax_histx.xaxis.set_tick_params(labelbottom=False)
46+
ax_histy.yaxis.set_tick_params(labelleft=False)
3647

3748
# now determine nice limits by hand:
3849
binwidth = 0.25
3950
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
4051
lim = (int(xymax/binwidth) + 1)*binwidth
4152

4253
bins = np.arange(-lim, lim + binwidth, binwidth)
43-
axHistx.hist(x, bins=bins)
44-
axHisty.hist(y, bins=bins, orientation='horizontal')
54+
ax_histx.hist(x, bins=bins)
55+
ax_histy.hist(y, bins=bins, orientation='horizontal')
4556

46-
# the xaxis of axHistx and yaxis of axHisty are shared with axScatter,
57+
# the xaxis of ax_histx and yaxis of ax_histy are shared with ax,
4758
# thus there is no need to manually adjust the xlim and ylim of these
4859
# axis.
4960

50-
axHistx.set_yticks([0, 50, 100])
51-
52-
axHisty.set_xticks([0, 50, 100])
61+
ax_histx.set_yticks([0, 50, 100])
62+
ax_histy.set_xticks([0, 50, 100])
5363

5464
plt.show()
65+
66+
#############################################################################
67+
#
68+
# ------------
69+
#
70+
# References
71+
# """"""""""
72+
#
73+
# The use of the following functions, methods and classes is shown
74+
# in this example:
75+
76+
import matplotlib, mpl_toolkits
77+
mpl_toolkits.axes_grid1.axes_divider.make_axes_locatable
78+
matplotlib.axes.Axes.set_aspect
79+
matplotlib.axes.Axes.scatter
80+
matplotlib.axes.Axes.hist

examples/lines_bars_and_markers/scatter_hist.py

Lines changed: 97 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,18 +3,62 @@
33
Scatter plot with histograms
44
============================
55
6-
Create a scatter plot with histograms to its sides.
6+
Show the marginal distributions of a scatter as histograms at the sides of
7+
the plot.
8+
9+
For a nice alignment of the main axes with the marginals, two options are shown
10+
below.
11+
12+
* the axes positions are defined in terms of rectangles in figure coordinates
13+
* the axes positions are defined via a gridspec
14+
15+
An alternative method to produce a similar figure using the ``axes_grid1``
16+
toolkit is shown in the
17+
:doc:`/gallery/axes_grid1/scatter_hist_locatable_axes` example.
18+
19+
Let us first define a function that takes x and y data as input, as well
20+
as three axes, the main axes for the scatter, and two marginal axes. It will
21+
then create the scatter and histograms inside the provided axes.
722
"""
23+
824
import numpy as np
925
import matplotlib.pyplot as plt
1026

1127
# Fixing random state for reproducibility
1228
np.random.seed(19680801)
1329

14-
# the random data
30+
# some random data
1531
x = np.random.randn(1000)
1632
y = np.random.randn(1000)
1733

34+
35+
def scatter_hist(x, y, ax, ax_histx, ax_histy):
36+
# no labels
37+
ax_histx.tick_params(axis="x", labelbottom=False)
38+
ax_histy.tick_params(axis="y", labelleft=False)
39+
40+
# the scatter plot:
41+
ax.scatter(x, y)
42+
43+
# now determine nice limits by hand:
44+
binwidth = 0.25
45+
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
46+
lim = (int(xymax/binwidth) + 1) * binwidth
47+
48+
bins = np.arange(-lim, lim + binwidth, binwidth)
49+
ax_histx.hist(x, bins=bins)
50+
ax_histy.hist(y, bins=bins, orientation='horizontal')
51+
52+
53+
#############################################################################
54+
#
55+
# Axes in figure coordinates
56+
# --------------------------
57+
#
58+
# To define the axes positions, `.Figure.add_axes` is provided with a rectangle
59+
# ``[left, bottom, width, height]`` in figure coordinates. The marginal axes
60+
# share one dimension with the main axes.
61+
1862
# definitions for the axes
1963
left, width = 0.1, 0.65
2064
bottom, height = 0.1, 0.65
@@ -25,30 +69,61 @@
2569
rect_histx = [left, bottom + height + spacing, width, 0.2]
2670
rect_histy = [left + width + spacing, bottom, 0.2, height]
2771

28-
# start with a rectangular Figure
29-
plt.figure(figsize=(8, 8))
72+
# start with a square Figure
73+
fig = plt.figure(figsize=(8, 8))
74+
75+
ax = fig.add_axes(rect_scatter)
76+
ax_histx = fig.add_axes(rect_histx, sharex=ax)
77+
ax_histy = fig.add_axes(rect_histy, sharey=ax)
78+
79+
# use the previously defined function
80+
scatter_hist(x, y, ax, ax_histx, ax_histy)
81+
82+
plt.show()
83+
3084

31-
ax_scatter = plt.axes(rect_scatter)
32-
ax_scatter.tick_params(direction='in', top=True, right=True)
33-
ax_histx = plt.axes(rect_histx)
34-
ax_histx.tick_params(direction='in', labelbottom=False)
35-
ax_histy = plt.axes(rect_histy)
36-
ax_histy.tick_params(direction='in', labelleft=False)
85+
#############################################################################
86+
#
87+
# Using a gridspec
88+
# ----------------
89+
#
90+
# We may equally define a gridspec with unequal width- and height-ratios to
91+
# achieve desired layout. Also see the :doc:`/tutorials/intermediate/gridspec`
92+
# tutorial.
3793

38-
# the scatter plot:
39-
ax_scatter.scatter(x, y)
94+
# start with a square Figure
95+
fig = plt.figure(figsize=(8, 8))
4096

41-
# now determine nice limits by hand:
42-
binwidth = 0.25
43-
lim = np.ceil(np.abs([x, y]).max() / binwidth) * binwidth
44-
ax_scatter.set_xlim((-lim, lim))
45-
ax_scatter.set_ylim((-lim, lim))
97+
# Add a gridspec with two rows and two columns and a ratio of 2 to 7 between
98+
# the size of the marginal axes and the main axes in both directions.
99+
# Also adjust the subplot parameters for a square plot.
100+
gs = fig.add_gridspec(2, 2, width_ratios=(7, 2), height_ratios=(2, 7),
101+
left=0.1, right=0.9, bottom=0.1, top=0.9,
102+
wspace=0.05, hspace=0.05)
46103

47-
bins = np.arange(-lim, lim + binwidth, binwidth)
48-
ax_histx.hist(x, bins=bins)
49-
ax_histy.hist(y, bins=bins, orientation='horizontal')
104+
ax = fig.add_subplot(gs[1, 0])
105+
ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
106+
ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
50107

51-
ax_histx.set_xlim(ax_scatter.get_xlim())
52-
ax_histy.set_ylim(ax_scatter.get_ylim())
108+
# use the previously defined function
109+
scatter_hist(x, y, ax, ax_histx, ax_histy)
53110

54111
plt.show()
112+
113+
114+
#############################################################################
115+
#
116+
# ------------
117+
#
118+
# References
119+
# """"""""""
120+
#
121+
# The use of the following functions, methods and classes is shown
122+
# in this example:
123+
124+
import matplotlib
125+
matplotlib.figure.Figure.add_axes
126+
matplotlib.figure.Figure.add_subplot
127+
matplotlib.figure.Figure.add_gridspec
128+
matplotlib.axes.Axes.scatter
129+
matplotlib.axes.Axes.hist

tutorials/toolkits/axes_grid.py

Lines changed: 24 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -3,21 +3,22 @@
33
Overview of axes_grid1 toolkit
44
==============================
55
6-
Controlling the layout of plots with the axes_grid toolkit.
6+
Controlling the layout of plots with the
7+
:mod:`mpl_toolkits.axes_grid1` toolkit.
78
89
.. _axes_grid1_users-guide-index:
910
1011
1112
What is axes_grid1 toolkit?
1213
===========================
1314
14-
*axes_grid1* is a collection of helper classes to ease displaying
15-
(multiple) images with matplotlib. In matplotlib, the axes location
15+
:mod:`mpl_toolkits.axes_grid1` is a collection of helper classes to ease
16+
displaying (multiple) images with matplotlib. In matplotlib, the axes location
1617
(and size) is specified in the normalized figure coordinates, which
1718
may not be ideal for displaying images that needs to have a given
1819
aspect ratio. For example, it helps if you have a colorbar whose
1920
height always matches that of the image. `ImageGrid`_, `RGB Axes`_ and
20-
`AxesDivider`_ are helper classes that deals with adjusting the
21+
`AxesDivider`_ are helper classes that deal with adjusting the
2122
location of (multiple) Axes. They provides a framework to adjust the
2223
position of multiple axes at the drawing time. `ParasiteAxes`_
2324
provides twinx(or twiny)-like features so that you can plot different
@@ -119,7 +120,7 @@
119120
*aspect*
120121
By default (False), widths and heights of axes in the grid are
121122
scaled independently. If True, they are scaled according to their
122-
data limits (similar to aspect parameter in mpl).
123+
data limits (similar to aspect parameter in Matplotlib).
123124
124125
*share_all*
125126
if True, xaxis and yaxis of all axes are shared.
@@ -161,19 +162,19 @@
161162
-----------------
162163
163164
Behind the scene, the ImageGrid class and the RGBAxes class utilize the
164-
AxesDivider class, whose role is to calculate the location of the axes
165-
at drawing time. While a more about the AxesDivider is (will be)
166-
explained in (yet to be written) AxesDividerGuide, direct use of the
167-
AxesDivider class will not be necessary for most users. The
168-
axes_divider module provides a helper function make_axes_locatable,
169-
which can be useful. It takes a existing axes instance and create a
170-
divider for it. ::
165+
`~.axes_grid1.axes_divider.AxesDivider` class, whose role is to calculate the
166+
location of the axes at drawing time. Direct use of the
167+
AxesDivider class will not be necessary for most users. The
168+
axes_divider module provides a helper function
169+
`~.axes_grid1.axes_divider.make_axes_locatable`, which can be useful.
170+
It takes a existing axes instance and create a divider for it. ::
171171
172172
ax = subplot(1, 1, 1)
173173
divider = make_axes_locatable(ax)
174174
175-
*make_axes_locatable* returns an instance of the AxesLocator class,
176-
derived from the Locator. It provides *append_axes* method that
175+
*make_axes_locatable* returns an instance of the
176+
`~.axes_grid1.axes_divider.AxesDivider` class. It provides an
177+
`~.AxesDivider.append_axes` method that
177178
creates a new axes on the given side of ("top", "right", "bottom" and
178179
"left") of the original axes.
179180
@@ -193,7 +194,7 @@
193194
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
194195
195196
The :doc:`/gallery/lines_bars_and_markers/scatter_hist` example can be
196-
rewritten using *make_axes_locatable*::
197+
rewritten using `~.axes_grid1.axes_divider.make_axes_locatable`::
197198
198199
axScatter = subplot(111)
199200
axScatter.scatter(x, y)
@@ -219,10 +220,11 @@
219220
220221
Scatter Hist
221222
222-
The scatter_hist using the AxesDivider has some advantage over the
223-
original scatter_hist.py in mpl. For example, you can set the aspect
224-
ratio of the scatter plot, even with the x-axis or y-axis is shared
225-
accordingly.
223+
The :doc:`/gallery/axes_grid1/scatter_hist_locatable_axes` using the
224+
AxesDivider has some advantage over the
225+
original :doc:`/gallery/lines_bars_and_markers/scatter_hist` in Matplotlib.
226+
For example, you can set the aspect ratio of the scatter plot, even with the
227+
x-axis or y-axis is shared accordingly.
226228
227229
228230
ParasiteAxes
@@ -297,7 +299,7 @@
297299
---------------
298300
299301
It's a collection of artists whose location is anchored to the (axes)
300-
bbox, like the legend. It is derived from *OffsetBox* in mpl, and
302+
bbox, like the legend. It is derived from *OffsetBox* in Matplotlib, and
301303
artist need to be drawn in the canvas coordinate. But, there is a
302304
limited support for an arbitrary transform. For example, the ellipse
303305
in the example below will have width and height in the data
@@ -391,8 +393,8 @@
391393
AxesDivider
392394
===========
393395
394-
The `~.axes_grid1.axes_divider` module provides helper classes to adjust the
395-
axes positions of a set of images at drawing time.
396+
The :mod:`mpl_toolkits.axes_grid1.axes_divider` module provides helper classes
397+
to adjust the axes positions of a set of images at drawing time.
396398
397399
* :mod:`~mpl_toolkits.axes_grid1.axes_size` provides a class of
398400
units that are used to determine the size of each axes. For example,

0 commit comments

Comments
 (0)