pandasとggplotで回帰分析
Python版ggplotの練習です。
コードと元データはこちらを参考にしました。
ITエンジニアのためのデータサイエンティスト養成講座(6):回帰分析I:回帰分析って何? から、最小二乗法、モデル評価、妥当性検討の実際まで (1/3) - @IT
import pandas as pd import numpy as np from ggplot import * # データを格納 df=pd.read_csv("children_data2005_08_130819.csv", encoding='shift-jis', skiprows=2, header=-1) df=df[np.isfinite(df[9])] # 欠損したデータは除く df=df[np.isfinite(df[10])] # 欠損したデータは除く # 身長と体重をプロット g=ggplot(aes("height","weight"), data=df[[9,10]])+geom_point() g
ggplotでプロットできました。
# 最小二乗法 model=pd.ols(x=height, y=weight, intercept=True) model
# 回帰直線をプロット g+geom_line(data=pd.DataFrame({"height":model.x["x"], "weight":model.y_fitted}), color="green”)
# 「体重は身長の3乗に比例する」というモデル model2=pd.ols(x=height**3, y=weight, intercept=True) model2
ggplot(aes("x","y"), data=pd.DataFrame({"x":model2.x["x"], "y":model2.y}))+\ geom_point()+\ geom_line(data=pd.DataFrame({"x":model2.x["x"], "y":model2.y_fitted}),color="red”)
ggplotで図を重ねるときにハマりやすいポイントとしては、 ggplot(aes=(“”,””), data=~)で指定したaesの文字列と、 geom_line(data~)ので指定したデータフレームのヘッダーが一致していないといけないということです。
過去記事
Python版ggplotで日本語を使う - Dimension Planet Adventure 最終章 最終話『栄光なる未来』 Python3.4にPython版ggplotをインストールしたい - Dimension Planet Adventure 最終章 最終話『栄光なる未来』
Pythonによるデータ分析入門 ―NumPy、pandasを使ったデータ処理
- 作者: Wes McKinney,小林儀匡,鈴木宏尚,瀬戸山雅人,滝口開資,野上大介
- 出版社/メーカー: オライリージャパン
- 発売日: 2013/12/26
- メディア: 大型本
- この商品を含むブログ (5件) を見る
- 作者: 小池壮彦
- 出版社/メーカー: 学研マーケティング
- 発売日: 2014/07/08
- メディア: 新書
- この商品を含むブログを見る