はじめに
このチュートリアルでは、Python の Matplotlib ライブラリを使って「パイチャートの棒グラフ」を作成する方法を学びます。パイチャートの棒グラフは、パイチャートと積み上げ棒グラフの組み合わせで、パイの最初のスライスがその特性をさらに細分化した棒グラフに展開されます。このグラフは、全体のデータセットの分布を示しながら、特定のカテゴリを強調したい場合に便利です。
VM のヒント
VM の起動が完了したら、左上隅をクリックしてノートブックタブに切り替え、Jupyter Notebook を使って練習しましょう。
時々、Jupyter Notebook が読み込み終了するまで数秒待つ必要がある場合があります。Jupyter Notebook の制限により、操作の検証を自動化することはできません。
学習中に問題に遭遇した場合は、Labby にお問い合わせください。セッション後にフィードバックを提供してください。すぐに問題を解決いたします。
必要なライブラリをインポートする
グラフを作成する前に、必要なライブラリをインポートする必要があります。この場合、matplotlib.pyplot と numpy を使用します。
import matplotlib.pyplot as plt
import numpy as np
グラフ用のデータを定義する
次に、グラフを作成するために使用するデータを定義する必要があります。この場合、次のデータを使用します。
## pie chart parameters
overall_ratios = [.27,.56,.17]
labels = ['Approve', 'Disapprove', 'Undecided']
explode = [0.1, 0, 0]
## bar chart parameters
age_ratios = [.33,.54,.07,.06]
age_labels = ['Under 35', '35-49', '50-65', 'Over 65']
パイチャートを作成する
これでパイチャートを作成できます。まず、グラフと軸のオブジェクトを定義します。
## make figure and assign axis objects
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 5))
fig.subplots_adjust(wspace=0)
次に、パイチャートのパラメータを設定してプロットします。
## rotate so that first wedge is split by the x-axis
angle = -180 * overall_ratios[0]
wedges, *_ = ax1.pie(overall_ratios, autopct='%1.1f%%', startangle=angle,
labels=labels, explode=explode)
棒グラフを作成する
次に、積み上げ棒グラフを作成します。まず、グラフのパラメータを定義します。
## bar chart parameters
bottom = 1
width =.2
## Adding from the top matches the legend.
for j, (height, label) in enumerate(reversed([*zip(age_ratios, age_labels)])):
bottom -= height
bc = ax2.bar(0, height, width, bottom=bottom, color='C0', label=label,
alpha=0.1 + 0.25 * j)
ax2.bar_label(bc, labels=[f"{height:.0%}"], label_type='center')
パイチャートと棒グラフを接続する
最後に、ConnectionPatch を使ってパイチャートと棒グラフを接続します。
## use ConnectionPatch to draw lines between the two plots
theta1, theta2 = wedges[0].theta1, wedges[0].theta2
center, r = wedges[0].center, wedges[0].r
bar_height = sum(age_ratios)
## draw top connecting line
x = r * np.cos(np.pi / 180 * theta2) + center[0]
y = r * np.sin(np.pi / 180 * theta2) + center[1]
con = ConnectionPatch(xyA=(-width / 2, bar_height), coordsA=ax2.transData,
xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
con.set_linewidth(4)
ax2.add_artist(con)
## draw bottom connecting line
x = r * np.cos(np.pi / 180 * theta1) + center[0]
y = r * np.sin(np.pi / 180 * theta1) + center[1]
con = ConnectionPatch(xyA=(-width / 2, 0), coordsA=ax2.transData,
xyB=(x, y), coordsB=ax1.transData)
con.set_color([0, 0, 0])
ax2.add_artist(con)
con.set_linewidth(4)
グラフを表示する
最後に、グラフを表示します。
plt.show()
まとめ
このチュートリアルでは、Python の Matplotlib ライブラリを使って「パイチャートの棒グラフ」を作成する方法を学びました。パイチャートの棒グラフは、全体のデータセットの分布を示しながら、特定のカテゴリを強調したい場合に便利です。また、ConnectionPatchを使ってパイチャートと棒グラフを接続する方法も学びました。