はじめに
この実験では、Matplotlib ライブラリを使って Python でハットグラフを作成する方法を学びます。ハットグラフは、積み上げ棒グラフの一種で、各棒がハットの形をしています。ゲームの数とプレイヤーによる得点のデータセットを使ってグラフを作成します。
VM のヒント
VM の起動が完了したら、左上隅をクリックして ノートブック タブに切り替えて、Jupyter Notebook を使って練習します。
時々、Jupyter Notebook が読み込み終わるまで数秒待つ必要があります。Jupyter Notebook の制限により、操作の検証は自動化できません。
学習中に問題がある場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。
ライブラリのインポート
このステップでは、ハットグラフを作成するために必要なライブラリをインポートします。
import matplotlib.pyplot as plt
import numpy as np
ハットグラフ関数の定義
このステップでは、ハットグラフを作成する関数を定義します。この関数には以下のパラメータが必要です。
- ax: プロットする Axes。
- xlabels: x 軸に表示するカテゴリ名。
- values: データ値。行はグループ、列はカテゴリです。
- group_labels: 凡例に表示するグループラベル。
def hat_graph(ax, xlabels, values, group_labels):
"""
Create a hat graph.
Parameters
----------
ax : matplotlib.axes.Axes
The Axes to plot into.
xlabels : list of str
The category names to be displayed on the x-axis.
values : (M, N) array-like
The data values.
Rows are the groups (len(group_labels) == M).
Columns are the categories (len(xlabels) == N).
group_labels : list of str
The group labels displayed in the legend.
"""
def label_bars(heights, rects):
"""Attach a text label on top of each bar."""
for height, rect in zip(heights, rects):
ax.annotate(f'{height}',
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 4), ## 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom')
values = np.asarray(values)
x = np.arange(values.shape[1])
ax.set_xticks(x, labels=xlabels)
spacing = 0.3 ## spacing between hat groups
width = (1 - spacing) / values.shape[0]
heights0 = values[0]
for i, (heights, group_label) in enumerate(zip(values, group_labels)):
style = {'fill': False} if i == 0 else {'edgecolor': 'black'}
rects = ax.bar(x - spacing/2 + i * width, heights - heights0,
width, bottom=heights0, label=group_label, **style)
label_bars(heights, rects)
データの準備
このステップでは、ラベルと numpy 配列を初期化します。配列内に N 個の値の N 個のラベルがあることを確認します。
## initialise labels and a numpy array make sure you have
## N labels of N number of values in the array
xlabels = ['I', 'II', 'III', 'IV', 'V']
playerA = np.array([5, 15, 22, 20, 25])
playerB = np.array([25, 32, 34, 30, 27])
ハットグラフの作成
このステップでは、前のステップで準備したデータと hat_graph 関数を使ってハットグラフを作成します。
fig, ax = plt.subplots()
hat_graph(ax, xlabels, [playerA, playerB], ['Player A', 'Player B'])
## Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xlabel('Games')
ax.set_ylabel('Score')
ax.set_ylim(0, 60)
ax.set_title('Scores by number of game and players')
ax.legend()
fig.tight_layout()
plt.show()
完成コード
以下は、Python でハットグラフを作成するための完成コードです。
import matplotlib.pyplot as plt
import numpy as np
def hat_graph(ax, xlabels, values, group_labels):
"""
Create a hat graph.
Parameters
----------
ax : matplotlib.axes.Axes
The Axes to plot into.
xlabels : list of str
The category names to be displayed on the x-axis.
values : (M, N) array-like
The data values.
Rows are the groups (len(group_labels) == M).
Columns are the categories (len(xlabels) == N).
group_labels : list of str
The group labels displayed in the legend.
"""
def label_bars(heights, rects):
"""Attach a text label on top of each bar."""
for height, rect in zip(heights, rects):
ax.annotate(f'{height}',
xy=(rect.get_x() + rect.get_width() / 2, height),
xytext=(0, 4), ## 4 points vertical offset.
textcoords='offset points',
ha='center', va='bottom')
values = np.asarray(values)
x = np.arange(values.shape[1])
ax.set_xticks(x, labels=xlabels)
spacing = 0.3 ## spacing between hat groups
width = (1 - spacing) / values.shape[0]
heights0 = values[0]
for i, (heights, group_label) in enumerate(zip(values, group_labels)):
style = {'fill': False} if i == 0 else {'edgecolor': 'black'}
rects = ax.bar(x - spacing/2 + i * width, heights - heights0,
width, bottom=heights0, label=group_label, **style)
label_bars(heights, rects)
## initialise labels and a numpy array make sure you have
## N labels of N number of values in the array
xlabels = ['I', 'II', 'III', 'IV', 'V']
playerA = np.array([5, 15, 22, 20, 25])
playerB = np.array([25, 32, 34, 30, 27])
fig, ax = plt.subplots()
hat_graph(ax, xlabels, [playerA, playerB], ['Player A', 'Player B'])
## Add some text for labels, title and custom x-axis tick labels, etc.
ax.set_xlabel('Games')
ax.set_ylabel('Score')
ax.set_ylim(0, 60)
ax.set_title('Scores by number of game and players')
ax.legend()
fig.tight_layout()
plt.show()
まとめ
この実験では、Matplotlib ライブラリを使って Python でハットグラフを作成する方法を学びました。ハットグラフを作成する関数を定義し、データを準備し、hat_graph 関数を使ってグラフを作成しました。ハットグラフは、積み上げ棒グラフのバリエーションで、各棒がハットの形をしています。グラフを作成するために、試合数とプレイヤーによる得点のデータセットを使用しました。