'22/09/10更新:グリッド設定の引数を追加(明記)しました。
本記事では、下図のような積み上げ棒グラフを作成する雛形コードを載せました。次のサイトを参考にして、自分好みの設定にしたものです。https://pystyle.info/matplotlib-stacked-bar-chart/
上図の元データは下記です。凡例はB列より右側の列名です。x軸ラベルはA列にある行名です。
ちなみに、住居は家賃のことで、住宅ローンは含まれないために低めの値です。そして、住宅ローンの他に貯金と保険は、家計調査の消費支出に含まれないようです。
■本プログラム
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import japanize_matplotlib
plt.rcParams['font.size'] = 15
file_name = '2人以上世帯の年代別の生活費'
file_path = file_name + '.xlsx'
df = pd.read_excel(file_path,
sheet_name = 'Sheet1',
engine = "openpyxl")
df
df.set_index('年代', inplace=True)
df
DF = df.iloc[::-1]
DF
n_rows, n_cols = DF.shape
positions = np.arange(n_rows)
offsets = np.zeros(n_rows, dtype=DF.values.dtype)
colors = plt.get_cmap("tab20c")(np.linspace(0, 1, n_cols))
fig, ax = plt.subplots(figsize=(8, 7))
ax.set_xticks(positions)
ax.set_xticklabels(DF.index)
for i in range(len(DF.columns)):
bar = ax.bar(positions, DF.iloc[:, i], bottom=offsets,
color=colors[i], label=DF.columns[i])
offsets += DF.iloc[:, i]
for rect, value in zip(bar, DF.iloc[:, i]):
cx = rect.get_x() + rect.get_width() * 0.5
cy = rect.get_y() + rect.get_height() * 0.5
ax.text(cx, cy, '{:.1f}'.format(value),
color = "k", ha = "center", va = "center")
plt.title(file_name)
plt.ylabel(r'消費支出 [万円/月]')
plt.ylim(0, 40)
plt.legend(bbox_to_anchor=(1,1))
plt.grid(axis = 'y', linestyle = 'dashed', color = 'gray')
plt.show()
以上
<広告>
リンク
リンク