Python 帯グラフを作成する

 本記事では、下図のような帯グラフ(積み重ね棒グラフ)の雛形コードを載せました。

f:id:HK29:20210529235413p:plain

次のサイトを参考にさせて頂き、前処理の追加や私好みに多少編集しています。matplotlib - 積み上げ棒グラフを作成する方法 - pystyle

使用したデータは下図のようなcsvファイルを用いました。数値は、次のリンク先を引用しました。http://www.stat.go.jp/naruhodo/4_graph/shokyu/obi-graph.html

f:id:HK29:20210530000036p:plain

これをpandasでソートや正規化などの処理をしてから、冒頭のようなグラフにします。

■本プログラム

#!/usr/bin/env python
# coding: utf-8

# In[1]:


import pandas as pd
from matplotlib import pyplot as plt
import japanize_matplotlib
import matplotlib.cm as cm

df = pd.read_csv('産業別就業者数の構成率の推移.csv',
                 sep = ',',
                 encoding = 'cp932')
df


# In[2]:


# インデックスで降順にソートする
df.sort_index(ascending=False, inplace=True)
df


# In[3]:


# 年代をインデックスにする
df.set_index('年代', inplace=True)
df


# In[4]:


# データの正規化(各行の和を1にする)
DF = df.div(df.sum(axis=1), axis=0)
DF


# In[5]:


# データの行列数を取得
rows, cols = df.shape
print(rows, cols)


# In[6]:


# 棒グラフを描くためのラベル座標をリストで作成
y_position_list = list(range(rows))
y_position_list


# In[9]:


# 帯グラフを作成するセル
plt.rcParams['font.size'] = 14

fig, ax = plt.subplots()

# 帯グラフ(積み重ね棒グラフ)を描くためのx座標初期値
x_offset = [0] * rows
x_offset
# 横棒グラフ作成
for i, my_col in enumerate(df.columns):
    my_col_data = DF[my_col] # 各列のデータ
    #print(i, my_col, my_col_data)
    bar = ax.barh(
        y = y_position_list, # y軸の座標
        width = my_col_data, # xデータ(棒グラフを積み上げてゆく)
        height = 0.8,
        left = x_offset, # x軸座標
        color = cm.hot(i/rows),
        label = my_col
    )
    # 棒グラフを二つ目以降積み重ねるためにx座標をずらす
    x_offset += my_col_data
    
    for rect, val in zip(bar, my_col_data):
        cx = rect.get_x() + rect.get_width() * 0.5
        cy = rect.get_y() + rect.get_height() * 0.5
        ax.text(cx, cy,
                "{:.0%}".format(val), # %表記
                color = 'white', # 文字色の指定 'white' 'black'
                ha = 'center', va = 'center' # 文字の位置
        )
ax.set_xlim(0, 1)
ax.set_yticks(y_position_list) # y軸ラベルの座標をセット
ax.set_yticklabels(DF.index) # y軸ラベルを記載
ax.legend(bbox_to_anchor=(1, 0.95)) # 凡例の位置


# In[ ]:

以上

<広告>