Matplotlibの円グラフ#
※記事内に商品プロモーションを含むことがあります。
公開日
Matplotlibで円グラフを出力するには、ax.pie
を使用します。ax.pie
の引数に数値の配列を与えます。
import matplotlib.pyplot as plt
x = [9, 7, 5, 3]
fig, ax = plt.subplots()
ax.pie(x)
plt.show()

デフォルトの設定では、時計の3時の位置を0度として、反時計周りにプロットします。また、円グラフの中心座標は(0, 0), 半径は1となります。
ax.pieのオプション#
ax.pie
の主なオプションを以下に示します。
labels
(list): データのラベルlabeldistance
(float): ラベルの中心からの距離(デフォルト:1.1)textprops
(dict): テキストの書式を指定colors
(list): グラフの色explode
(list): グラフの要素を中心から切り離すpctdistance
(float): 数値の中心からの距離(デフォルト:0.6)autopct
(str): 割合を表示するshadow
(bool):True
の場合、グラフに影を付ける(デフォルト:False
)startangle
(float): グラフの開始角度(degree, デフォルト:0)counterclock
(bool):True
の場合、データを反時計回りに並べる(デフォルト:True
)wedgeprops
(dict): グラフの要素の書式を指定radius
(float): 円グラフの半径(デフォルト:1)
データのラベル#
labels
オプションにデータのラベルを配列で与えることができます。
labels = ["Alice", "Bob", "Carol", "Dave"]
fig, ax = plt.subplots()
ax.pie(x, labels=labels)
plt.show()

フォントの設定を変更するには、textprops
オプションを用います。文字の大きさを変更する場合、以下のようにfontsize
をキーとした辞書形式で与えます。
fig, ax = plt.subplots()
ax.pie(x, labels=labels, textprops={"fontsize": 15})
plt.show()

グラフの色を変更#
グラフの色を変更するには、色のリストをcolors
オプションに渡します。color
オプションの詳細は以下の記事を参考にして下さい。
colors = ["black", "brown", "pink", "purple"]
fig, ax = plt.subplots()
ax.pie(x, labels=labels, colors=colors)
plt.show()

グラフの要素を切り離す#
グラフの要素を中心から切り離した円グラフを作成するには、explode
オプションを用います。グラフの中心からのオフセット量を配列として与えます。位置を変更しない要素については0
とします。
explode = [0.2, 0.1, 0, 0]
fig, ax = plt.subplots()
ax.pie(x, labels=labels, explode=explode)
plt.show()

データの割合を表示#
データの割合を円グラフ内に表示するには、autopct
オプションを用います。autopct
に書式を渡します。書式の例を以下の表に示します。
|
例 |
---|---|
|
|
|
|
|
|
|
|
fig, ax = plt.subplots()
ax.pie(x, labels=labels, autopct="%1.1f%%")
plt.show()

また、数値の中心からの距離はpctdistance
オプションで指定可能です(デフォルト値は0.6
)。
fig, ax = plt.subplots()
ax.pie(x, labels=labels, autopct="%1.1f%%", pctdistance=0.8)
plt.show()

グラフに影を付ける#
グラフに影を付けるには、shadow=True
とします。
explode = [0.1, 0, 0, 0]
fig, ax = plt.subplots()
ax.pie(x, labels=labels, shadow=True, explode=explode)
plt.show()

開始角度を変更#
円グラフの開始角度を変更するには、startangle
オプションに開始角度(度)を与えます。デフォルト値は0
で、時計の3時の方向です。startangle
の値が大きいほど、開始角度は反時計回りに増えます。
なお、counterclock=False
としてグラフを時計回りとした場合でも、startangle
オプションには影響しません。
以下は開始角度を90度(時計の12時の位置)とした例です。
fig, ax = plt.subplots()
ax.pie(x, labels=labels, startangle=90)
plt.show()

時計回りのグラフ#
グラフを時計回りにするには、counterclock=False
と設定します。
fig, ax = plt.subplots()
ax.pie(x, labels=labels, counterclock=False)
plt.show()

時計回りとして、さらに開始角度を90度(時計の12時の位置)とした円グラフの例を以下に示します。
fig, ax = plt.subplots()
ax.pie(x, labels=labels, startangle=90, counterclock=False)
plt.show()

枠線を付ける#
グラフに枠線を付けるには、wedgeprops
オプションを用います。wedgeprops
は辞書形式で指定し、linewidth
キーに枠線の太さ、edgecolor
キーに枠線の色をそれぞれ指定します。
fig, ax = plt.subplots()
ax.pie(x, labels=labels, wedgeprops={"linewidth": 1.5, "edgecolor": "black"})
plt.show()

凡例を表示#
グラフに反映を表示するには、ax.legend
にラベルを渡します。また、bbox_to_anchor
オプションで位置を調整できます。
fig, ax = plt.subplots()
ax.pie(x)
ax.legend(labels, bbox_to_anchor=(1, 0.9))
plt.show()

ax.legend
の詳細については、以下の記事を参照ください。