Pandasで成人喫煙率(JT全国喫煙者率調査)の表からグラフ作成

www.health-net.or.jp

スクレイピング・前処理

import pandas as pd

# 表を取得
dfs = pd.read_html("http://www.health-net.or.jp/tobacco/product/pd090000.html", header=0)

df = dfs[0]

# 列名確認
df.columns

# 列名置換
df.rename(columns={'Unnamed: 1':"性別"}, inplace=True)

# 確認
df

# 西暦にする
df["年"] = df.index // 2 + 1965

# 年度の列を削除
df.drop("年度", axis=1, inplace=True)

# 並び替え
df1 = df.pivot(index="年", columns="性別")

# 確認
df1

# 列名確認
df1.columns

# 列名レベル入替
df2 = df1.swaplevel(0, 1, axis=1)

# 列を男女に分ける
df3 = df2[["男", "女"]]

df3

グラフ

import matplotlib.pyplot as plt
import japanize_matplotlib

df3.plot(title="年代別喫煙率の推移")
plt.legend(bbox_to_anchor=(1.05, 1), loc='upper left', borderaxespad=0, fontsize=8)

# グラフを保存
plt.savefig('01.png', dpi=200, bbox_inches="tight")

plt.show()