yakataの情報奮闘記

プログラミングの話をします

matplotlib (Python) でsubplot使うときの書き方備忘録

特段加筆するなら、plotをたくさんするとなんのグラフなのかを示すものが必要になるので、一意なtitleをつけるなどすること(いつも忘れる) →もっといい書き方が最後にあります。

# 整数の各変数に対してboxplotを書きたいとする。Pandas DataFrameは変数dfに入っている。
# subplotのためにindexを取る必要があるので、enumerateを取る。
# 整数の各変数に対してboxplotを書きたいとする。Pandas DataFrameは変数dfに入っている。
# subplotのためにindexを取る必要があるので、enumerateを取る。
plt.figure(figsize=(20, 20))
for idx, column_name in enumerate(df.describe().columns.to_list()):
    # ここ↓のx,yはx*y<=カラム数になるようにint値に変更する。
    plt.subplot(x, y, idx+1)
    plt.boxplot(student_data_math[column_name])
    plt.title(column_name)
    plt.grid(True)

追記 以下のようにかける。参考文献は以下

df.select_dtypes(include=int)

pandas.DataFrameから特定の型dtypeの列を抽出(選択) | note.nkmk.me