凡例付き散布図の作成

Beginner

This tutorial is from open-source community. Access the source code

はじめに

散布図は、2 つの変数間の関係を視覚化するために使用されます。凡例付きの散布図は、データに複数のグループがあり、それらを散布図で区別したい場合に便利です。この実験では、Matplotlib ライブラリを使って Python で凡例付きの散布図を作成する方法を学びます。

VM のヒント

VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。

時々、Jupyter Notebook が読み込み完了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。

学習中に問題に直面した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。

必要なライブラリのインポート

まず、NumPy や Matplotlib などの必要なライブラリをインポートします。

import matplotlib.pyplot as plt
import numpy as np

複数のグループを持つ散布図の作成

各グループをループしてそのグループ用の散布図を作成することで、複数のグループを持つ散布図を作成できます。それぞれのグループに対して、マーカーの色、サイズ、透明度をそれぞれcsalphaパラメータを使って指定します。また、凡例に表示されるグループ名をlabelパラメータに設定します。

fig, ax = plt.subplots()
for color in ['tab:blue', 'tab:orange', 'tab:green']:
    n = 750
    x, y = np.random.rand(2, n)
    scale = 200.0 * np.random.rand(n)
    ax.scatter(x, y, c=color, s=scale, label=color,
               alpha=0.3, edgecolors='none')

ax.legend()
ax.grid(True)

plt.show()

自動凡例作成

散布図の凡例を自動的に作成するには、PathCollection.legend_elementsメソッドを使用することもできます。このメソッドは、表示する凡例エントリの有用な数を判断しようとし、ハンドルとラベルのタプルを返します。

N = 45
x, y = np.random.rand(2, N)
c = np.random.randint(1, 5, size=N)
s = np.random.randint(10, 220, size=N)

fig, ax = plt.subplots()

scatter = ax.scatter(x, y, c=c, s=s)

## produce a legend with the unique colors from the scatter
legend1 = ax.legend(*scatter.legend_elements(),
                    loc="lower left", title="Classes")
ax.add_artist(legend1)

## produce a legend with a cross-section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes")

plt.show()

凡例要素のカスタマイズ

PathCollection.legend_elementsメソッドに追加の引数を使うことで、凡例要素をさらにカスタマイズできます。たとえば、作成する凡例エントリの数とそれらのラベル付け方法を指定できます。

volume = np.random.rayleigh(27, size=40)
amount = np.random.poisson(10, size=40)
ranking = np.random.normal(size=40)
price = np.random.uniform(1, 10, size=40)

fig, ax = plt.subplots()

## Because the price is much too small when being provided as size for ``s``,
## we normalize it to some useful point sizes, s=0.3*(price*3)**2
scatter = ax.scatter(volume, amount, c=ranking, s=0.3*(price*3)**2,
                     vmin=-3, vmax=3, cmap="Spectral")

## Produce a legend for the ranking (colors). Even though there are 40 different
## rankings, we only want to show 5 of them in the legend.
legend1 = ax.legend(*scatter.legend_elements(num=5),
                    loc="upper left", title="Ranking")
ax.add_artist(legend1)

## Produce a legend for the price (sizes). Because we want to show the prices
## in dollars, we use the *func* argument to supply the inverse of the function
## used to calculate the sizes from above. The *fmt* ensures to show the price
## in dollars. Note how we target at 5 elements here, but obtain only 4 in the
## created legend due to the automatic round prices that are chosen for us.
kw = dict(prop="sizes", num=5, color=scatter.cmap(0.7), fmt="$ {x:.2f}",
          func=lambda s: np.sqrt(s/.3)/3)
legend2 = ax.legend(*scatter.legend_elements(**kw),
                    loc="lower right", title="Price")

plt.show()

まとめ

この実験では、Matplotlib ライブラリを使って Python で凡例付きの散布図を作成する方法を学びました。複数のグループを持つ散布図を作成し、凡例の自動作成も行いました。また、PathCollection.legend_elementsメソッドを使って凡例要素をカスタマイズしました。凡例付きの散布図は、複数のグループを持つ 2 つの変数間の関係を視覚化するのに役立ちます。