Python の Matplotlib を使ってレーダーチャートを作成する

PythonPythonBeginner
今すぐ練習

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

💡 このチュートリアルは英語版からAIによって翻訳されています。原文を確認するには、 ここをクリックしてください

はじめに

この実験では、PythonのMatplotlibライブラリを使ってレーダーチャートを作成する方法を学びます。レーダーチャートは、スパイダーチャートまたはスターチャートとも呼ばれ、同じ点から始まる軸上に表される3つ以上の量的変数の2次元チャートの形式で多変量データを表示するグラフィカルな方法です。これは、いくつかの要因に基づいて異なる製品やソリューションを比較するためによく使われます。

VMのヒント

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

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

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

ライブラリのインポート

まず、必要なライブラリをインポートする必要があります。このチュートリアルではMatplotlibとnumpyが必要です。

import matplotlib.pyplot as plt
import numpy as np

レーダーチャート関数の定義

次に、レーダーチャートを作成する関数を定義します。この関数は2つの引数を取ります。num_varsframeです。num_varsはレーダーチャートの変数の数であり、frameは軸を囲む枠の形状を指定します。

from matplotlib.patches import Circle, RegularPolygon
from matplotlib.path import Path
from matplotlib.projections import register_projection
from matplotlib.projections.polar import PolarAxes
from matplotlib.spines import Spine
from matplotlib.transforms import Affine2D

def radar_factory(num_vars, frame='circle'):
    ## 関数のコードはここに記載します

レーダー変換とレーダー軸クラスの定義

radar_factory関数の中で、RadarTransformRadarAxesクラスを定義します。これらのクラスは、レーダーチャートを作成するために使用されます。

class RadarTransform(PolarAxes.PolarTransform):
    ## RadarTransformクラスのコードはここに記載します

class RadarAxes(PolarAxes):
    ## RadarAxesクラスのコードはここに記載します

fillplot メソッドの定義

RadarAxes クラスの中で、fillplot メソッドを定義します。これらのメソッドは、それぞれチャート内の領域を塗りつぶすためとデータ点をプロットするために使用されます。

class RadarAxes(PolarAxes):
    ## RadarAxesクラスのコードはここに記載します

    def fill(self, *args, closed=True, **kwargs):
        ## fillメソッドをオーバーライドする
        return super().fill(closed=closed, *args, **kwargs)

    def plot(self, *args, **kwargs):
        ## plotメソッドをオーバーライドする
        lines = super().plot(*args, **kwargs)
        for line in lines:
            self._close_line(line)

    def _close_line(self, line):
        ## 線を閉じるためのヘルパーメソッド
        x, y = line.get_data()
        if x[0]!= x[-1]:
            x = np.append(x, x[0])
            y = np.append(y, y[0])
            line.set_data(x, y)

set_varlabels_gen_axes_patch および _gen_axes_spines メソッドの定義

RadarAxes クラスの中で、set_varlabels_gen_axes_patch および _gen_axes_spines メソッドも定義します。これらのメソッドは、それぞれ変数のラベルを設定し、軸のパッチを生成し、軸のスパインを生成します。

class RadarAxes(PolarAxes):
    ## RadarAxesクラスのコードはここに記載します

    def set_varlabels(self, labels):
        self.set_thetagrids(np.degrees(theta), labels)

    def _gen_axes_patch(self):
        if frame == 'circle':
            return Circle((0.5, 0.5), 0.5)
        elif frame == 'polygon':
            return RegularPolygon((0.5, 0.5), num_vars,
                                  radius=.5, edgecolor="k")
        else:
            raise ValueError("Unknown value for 'frame': %s" % frame)

    def _gen_axes_spines(self):
        if frame == 'circle':
            return super()._gen_axes_spines()
        elif frame == 'polygon':
            spine = Spine(axes=self,
                          spine_type='circle',
                          path=Path.unit_regular_polygon(num_vars))
            spine.set_transform(Affine2D().scale(.5).translate(.5,.5)
                                + self.transAxes)
            return {'polar': spine}
        else:
            raise ValueError("Unknown value for 'frame': %s" % frame)

サンプルデータの定義

次に、レーダーチャートを作成するために使用するサンプルデータを定義します。このデータは、汚染源プロファイル推定に関する研究から取得されています。

def example_data():
    data = [
        ['Sulfate', 'Nitrate', 'EC', 'OC1', 'OC2', 'OC3', 'OP', 'CO', 'O3'],
        ('Basecase', [
            [0.88, 0.01, 0.03, 0.03, 0.00, 0.06, 0.01, 0.00, 0.00],
            [0.07, 0.95, 0.04, 0.05, 0.00, 0.02, 0.01, 0.00, 0.00],
            [0.01, 0.02, 0.85, 0.19, 0.05, 0.10, 0.00, 0.00, 0.00],
            [0.02, 0.01, 0.07, 0.01, 0.21, 0.12, 0.98, 0.00, 0.00],
            [0.01, 0.01, 0.02, 0.71, 0.74, 0.70, 0.00, 0.00, 0.00]]),
        ('With CO', [
            [0.88, 0.02, 0.02, 0.02, 0.00, 0.05, 0.00, 0.05, 0.00],
            [0.08, 0.94, 0.04, 0.02, 0.00, 0.01, 0.12, 0.04, 0.00],
            [0.01, 0.01, 0.79, 0.10, 0.00, 0.05, 0.00, 0.31, 0.00],
            [0.00, 0.02, 0.03, 0.38, 0.31, 0.31, 0.00, 0.59, 0.00],
            [0.02, 0.02, 0.11, 0.47, 0.69, 0.58, 0.88, 0.00, 0.00]]),
        ('With O3', [
            [0.89, 0.01, 0.07, 0.00, 0.00, 0.05, 0.00, 0.00, 0.03],
            [0.07, 0.95, 0.05, 0.04, 0.00, 0.02, 0.12, 0.00, 0.00],
            [0.01, 0.02, 0.86, 0.27, 0.16, 0.19, 0.00, 0.00, 0.00],
            [0.01, 0.03, 0.00, 0.32, 0.29, 0.27, 0.00, 0.00, 0.95],
            [0.02, 0.00, 0.03, 0.37, 0.56, 0.47, 0.87, 0.00, 0.00]]),
        ('CO & O3', [
            [0.87, 0.01, 0.08, 0.00, 0.00, 0.04, 0.00, 0.00, 0.01],
            [0.09, 0.95, 0.02, 0.03, 0.00, 0.01, 0.13, 0.06, 0.00],
            [0.01, 0.02, 0.71, 0.24, 0.13, 0.16, 0.00, 0.50, 0.00],
            [0.01, 0.03, 0.00, 0.28, 0.24, 0.23, 0.00, 0.44, 0.88],
            [0.02, 0.00, 0.18, 0.45, 0.64, 0.55, 0.86, 0.00, 0.16]])
    ]
    return data

変数の数を設定して軸の角度を計算する

ここでは、変数の数を設定し、numpyを使って均等に間隔を空けた軸の角度を計算します。

N = 9
theta = radar_factory(N, frame='polygon')

レーダーチャートを作成する

最後に、サンプルデータと RadarAxes クラスを使ってレーダーチャートを作成できます。

data = example_data()
spoke_labels = data.pop(0)

fig, axs = plt.subplots(figsize=(9, 9), nrows=2, ncols=2,
                        subplot_kw=dict(projection='radar'))
fig.subplots_adjust(wspace=0.25, hspace=0.20, top=0.85, bottom=0.05)

colors = ['b', 'r', 'g','m', 'y']
for ax, (title, case_data) in zip(axs.flat, data):
    ax.set_rgrids([0.2, 0.4, 0.6, 0.8])
    ax.set_title(title, weight='bold', size='medium', position=(0.5, 1.1),
                 horizontalalignment='center', verticalalignment='center')
    for d, color in zip(case_data, colors):
        ax.plot(theta, d, color=color)
        ax.fill(theta, d, facecolor=color, alpha=0.25, label='_nolegend_')
    ax.set_varlabels(spoke_labels)

labels = ('Factor 1', 'Factor 2', 'Factor 3', 'Factor 4', 'Factor 5')
legend = axs[0, 0].legend(labels, loc=(0.9,.95),
                          labelspacing=0.1, fontsize='small')

fig.text(0.5, 0.965, '5-Factor Solution Profiles Across Four Scenarios',
         horizontalalignment='center', color='black', weight='bold',
         size='large')

plt.show()

まとめ

この実験では、PythonのMatplotlibライブラリを使ってレーダーチャートを作成する方法を学びました。レーダーチャートは、同じ点から始まる軸に表された3つ以上の量的変数の2次元チャートの形式で多変量データを表示するグラフィカルな方法です。これは、いくつかの要因に基づいて異なる製品やソリューションを比較するためによく使用されます。