はじめに
この実験では、Matplotlib を使ってヒストグラム付きの散布図を作成する方法を案内します。ヒストグラム付きの散布図は、2 つの変数の分布とその関係を視覚化するための素晴らしい方法です。散布図は 2 つの変数間の関係を表示し、一方ヒストグラムはそれぞれの変数の分布を独立に示します。
VM のヒント
VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。
時々、Jupyter Notebook が読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。そうすれば、迅速に問題を解決します。
ライブラリのインポート
始める前に、必要なライブラリをインポートする必要があります。この実験では、Matplotlib と NumPy を使用します。
import matplotlib.pyplot as plt
import numpy as np
ランダムなデータの生成
散布図とヒストグラムに使用するために、いくつかのランダムなデータを生成します。
## Fixing random state for reproducibility
np.random.seed(19680801)
## Generate random data
x = np.random.randn(1000)
y = np.random.randn(1000)
scatter_hist 関数の定義
scatter_hist関数を定義する必要があります。この関数は、x と y のデータと、3 つの軸(散布図用の主軸と 2 つの余白軸)を引数に取り、与えられた軸の中に散布図とヒストグラムを作成します。
def scatter_hist(x, y, ax, ax_histx, ax_histy):
## Remove labels from the histograms
ax_histx.tick_params(axis="x", labelbottom=False)
ax_histy.tick_params(axis="y", labelleft=False)
## Create the scatter plot
ax.scatter(x, y)
## Determine nice limits by hand
binwidth = 0.25
xymax = max(np.max(np.abs(x)), np.max(np.abs(y)))
lim = (int(xymax/binwidth) + 1) * binwidth
bins = np.arange(-lim, lim + binwidth, binwidth)
ax_histx.hist(x, bins=bins)
ax_histy.hist(y, bins=bins, orientation='horizontal')
gridspec を使って軸の位置を定義する
ここでは、異なる幅と高さの比率を持つgridspecを定義して、望ましいレイアウトを実現します。また、軸を作成してscatter_hist関数に渡します。
## Start with a square Figure.
fig = plt.figure(figsize=(6, 6))
## Add a gridspec with two rows and two columns and a ratio of 1 to 4 between
## the size of the marginal axes and the main axes in both directions.
## Also adjust the subplot parameters for a square plot.
gs = fig.add_gridspec(2, 2, width_ratios=(4, 1), height_ratios=(1, 4),
left=0.1, right=0.9, bottom=0.1, top=0.9,
wspace=0.05, hspace=0.05)
## Create the Axes.
ax = fig.add_subplot(gs[1, 0])
ax_histx = fig.add_subplot(gs[0, 0], sharex=ax)
ax_histy = fig.add_subplot(gs[1, 1], sharey=ax)
## Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
inset_axes を使って軸の位置を定義する
マージナルを主軸の「外側」に配置するために、inset_axesも使用できます。このようにする利点は、主軸のアスペクト比を固定でき、マージナルは常に軸の位置に対して描画されるということです。
## Create a Figure, which doesn't have to be square.
fig = plt.figure(layout='constrained')
## Create the main axes, leaving 25% of the figure space at the top and on the right to position marginals.
ax = fig.add_gridspec(top=0.75, right=0.75).subplots()
## The main axes' aspect can be fixed.
ax.set(aspect=1)
## Create marginal axes, which have 25% of the size of the main axes.
## Note that the inset axes are positioned *outside* (on the right and the top) of the main axes,
## by specifying axes coordinates greater than 1.
## Axes coordinates less than 0 would likewise specify positions on the left and the bottom of the main axes.
ax_histx = ax.inset_axes([0, 1.05, 1, 0.25], sharex=ax)
ax_histy = ax.inset_axes([1.05, 0, 0.25, 1], sharey=ax)
## Draw the scatter plot and marginals.
scatter_hist(x, y, ax, ax_histx, ax_histy)
グラフを表示する
最後に、plt.show()を使ってグラフを表示できます。
plt.show()
まとめ
この実験では、Matplotlib を使ってヒストグラム付きの散布図を作成する方法を学びました。scatter_hist関数を定義し、乱数データを生成し、gridspec と inset_axes を使って軸の位置を定義し、グラフを表示しました。ヒストグラム付きの散布図は、2 つの変数の分布とその関係を視覚化するための素晴らしい方法です。