0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Python(Matplotlib)で円グラフや箱ひげ図を描くためのメモ

Posted at

はじめに

Matplotlibを使って、円グラフや箱ひげ図を作ります。Copilotにいろいろ聞きました。

円グラフ

以下のような関数を用意。

Python hoge1.py
#-------------------------
# 円グラフ(一つだけ)を作成
# 値を表示するカスタム関数
def custom_autopct_for_pie_chart(pct, all_values):
    total = sum(all_values)
    value = int(round(pct * total / 100.0))  # 値を計算
    return f'{value}'  # 値を返す

def make_pie_chart(value, label, str, colors, filename):
    print('draw ' + filename)

    # グラフの設定
    #my_explode = (0, 0, 0, 0, 0, 0.1)  # "最初の項目"を少し外に出す
    fig, ax = plt.subplots(figsize=(10, 10))
    wedges, texts, autotexts = ax.pie(
        value,
        startangle=90,
        colors=colors,
        autopct=lambda pct: custom_autopct_for_pie_chart(pct, value),  # autopctは自家製
        wedgeprops={'edgecolor': 'white', 'linewidth': 2},
        explode=my_explode,
        textprops=dict(fontsize=14),
        #labels=label,
        #labeldistance=1.2,
    )
    # autopctの文字サイズ変更
    for autotext in autotexts:
        autotext.set_fontsize(20)  # 文字サイズを変更

    # タイトルを追加
    plt.title(str)
    plt.legend(label, bbox_to_anchor=(1.05, 1), loc='upper right')  # ラベルを凡例として表示

    # 保存
    plt.savefig(filename)
    
    plt.show()

箱ひげ図

箱ひげ図はboxplotというそうです。

Python hoge2.py
# 箱ひげ図の作成
def make_boxplot(values, title_str, colors, filename, legend_flg=False):
    print('draw ' + filename)

    # 箱ひげ図=boxplot
    fig, ax = plt.subplots()
    box = ax.boxplot(values, patch_artist=True, labels=out_column_a)

    # 箱ひげ図の色を指定
    for patch, color in zip(box['boxes'], colors):
        patch.set_facecolor(color)
    
    # グラフのタイトルとラベルを設定
    ax.set_title(title_str)
    ax.set_xlabel('カテゴリー')
    ax.set_ylabel('歩数')

    # 保存
    plt.savefig(filename)

#    plt.show()

Copilotに聞きながら作れるので、今後はこのような関数を予め用意するメリットが薄れていくのか? とはいえ、仕様が理解できている関数の方が拡張性や保守性は高いからなぁ。

(おわり)

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?