LoginSignup
30
39

More than 5 years have passed since last update.

pandasのプロット機能を使いJupyter上で作図

Last updated at Posted at 2016-07-27

環境

OS X El Capitan 10.11.6
python: 2.7.11
pandas: 0.18.0
matplotlib: 1.5.1
numpy: 1.10.4
IPython: 4.1.2

初めに

Pythonによる作図のおすすめ10
Pythonには様々な作図方法があり、matplotlibというライブラリを使うのが基本です。ただそれは少し野暮ったいので楽にオシャレに描けるようにするseabornというラッパーがあります。これに満足できなかったら、Bokehとかがいいのかもしれません。ggplotはRで使用している方は馴染みやすいかもしれません。

ただ、どちらにしろデータ整形に必要となるpandasにもmatplotlibのラッパーとしてプロット機能があるので、それを使うことにします。以下のサイトあたりを拝見し勉強したのですが、バージョンの違いなのか表記に微妙に差があり少し混乱しました。
http://sinhrks.hatenablog.com/entry/2015/11/15/222543
http://qiita.com/hik0107/items/de5785f680096df93efa
http://qiita.com/y__sama/items/9676f148a66c16d8f47c
http://qiita.com/TomokIshii/items/d786d25c69f20a0fc3c8

私にとって一番のポイントだったのは;

DataFrame.plot()
とするのが最もシンプルな描画ですが、散布図だと
DataFrame.plot(kind='scatter')

DataFrame.plot.scatter()
の表記が見られ、どちらの方がいいのか(正しいのか)迷いましたが、pandas本家の"Visualization"の"Other Plots"に以下の記述があり納得しました。

You can also create these other plots using the methods DataFrame.plot.kind instead of providing the kind keyword argument. This makes it easier to discover plot methods and the specific arguments they use:

というわけで、どちらも正しいのですが
DataFrame.plot.scatter()
と書いておく方が分かりやすいでしょう、という点でした。

以下で描画までの流れ、気づいた点を簡単にまとめます。
matplotlib本家pandas本家を読めば分かることではありますが。

作図の流れ

ライブラリの読み込み

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

Jupyter notebook内で図を描画するコマンド

%matplotlib inline

データの取り込み

ファイルパスの指定
file_path="/Users/username/Documents/file_name.csv"

カンマ区切りファイル

data_frame=pd.read_csv(file_path)

タブ区切りファイル

data_frame=pd.read_table(file_path)

上記以外のファイル

data_frame=pd.read_table(file_path, sep='.') # "."の場合
sep='' #区切り文字

その他設定
header='' #読み飛ばしたい行数

読み込んだデータの確認

data_frame.head() #データフレームの初めの数行確認
data_frame.tail() #データフレームの最後の数行確認

データ抽出

列の抽出

data_frame['column_name'] #シリーズとして抽出
data_frame.column_name #上と同じこと
data_frame[['column_name1','column_name2']] #2列抽出

行の抽出

data_frame.ix['index_name'] #ixはインデックス参照するためのフィールド
data_frame[:n]#n行まで全て抽出
data_frame[data_frame['column_name'] > x]#column_name列の値がxより大きい行を抽出
data_frame.query('column_name==x & column_name==y') #2つ以上条件付けるならこれで。
data_frame.query('column_name==x | column_name==y') #orの場合

プロット

画面の分割(2X2など)と余白の指定

fig, axes = plt.subplots(2,2,figsize=(19,19))
plt.subplots_adjust(left=None, bottom=None, right=None, top=None, wspace=0.1, hspace=0.1)

散布図

for文内で何枚か作図する場合。iはカウンター数。
data_frame.plot(x='column1',y='column2',xlim=(x1,x2),linestyle='',marker='.',ax=axes.flatten()[i],color='k',title=title_list[i])

data_frame.plot.scatter(x='column1',y='column2',xlim=(x1,x2),ax=axes.flatten()[i],color='k',s=15,title=title_list[i])

どちらでもいけますが、(おそらく)plot.scatter()は1対1対応を想定しているため凡例が出ない。plot()の場合でx軸にインデックスを使用する場合はx=を省略できます。標準が折れ線グラフなので線(linestyle)をなくしてマーカー(marker)を指定することで散布図にしています。
NaNを含むカラムがあっても無視してプロットしてくれますが、2つのカラムから同時にプロットする場合はエラーが出る。描く領域を毎回変える必要がある。

.plot( )の中身

xlim=(x1,x2) #x範囲
ylim=(y1,y2) #y範囲
color='k' #色指定 k黒、r赤、b青、g緑、cシアン、mマゼンタ、w白、y黄
linestyle='-' # lsでも。-:solid, --:dashed, '':nothing
linewidth=1 # lwでも。
marker='.' #.:point, o:circle, v:triangle,s:square,+:plus, '':nothing
markersize=12 # msでも。
markeredgecolor='' # mecでも。
markeredgewidth=1 # mewでも。
markerfacecolor='' # mfcでも。
label='name' #凡例
ax=axes.flatten()[i] #i番目の場所に描画
yerr='' #y軸方向のエラーバー

.plot.scatter()の中身

s=20 #マーカーサイズ

凡例を入れるコマンド

axes.flatten( )[i].legend(loc='best') # 'upper right','center left','lower center','center'

その他注意点

  • pylabパッケージは使わないほうがいい。(from pylab import *)

http://yagays.github.io/blog/2014/08/15/ipython-notebook-matplotlib-inline/
http://qiita.com/HirofumiYashima/items/51d8dac9a784de356c5b
import numpy as np
import matplotlib.pyplot as plt

としてnumpyとpyplotをそれぞれ読み込むべき。pylabは乱暴なインポートのため名前のかぶる可能性あり。

よくお世話になるサイト

pandas全般。開発者メンバーの一人の方がよくまとめてくださっています。
http://sinhrks.hatenablog.com/entry/2015/04/28/235430

matplotlibのwiki
http://seesaawiki.jp/met-python/d/matplotlib

標準python、numpy、pandasを行ったり来たりするために
http://qiita.com/richi40/items/6b3af6f4b00d62dbe8e1

用語

  • Python (2.7)
    スクリプト言語。Perlよりスッキリ書ける(としか書けない)。海外ではRubyより人気。科学計算によく使われ、それに関連するライブラリが多い。

  • ライブラリ
    汎用性の高い複数のプログラムを、再利用可能な形でひとまとまりにしたもの。他のプログラムに何らかの機能を提供するコードの集まり。標準で組み込まれている以下のモジュールやパッケージは標準ライブラリと呼ばれる。

  • モジュール
    関数のような部品を、利用目的ごとにまとめたもの。math, sysなど。

  • パッケージ
    モジュールとなるファイルを収めたディレクトリ。NumPy, pandasなど。

  • pandas
    扱いやすいデータ構造と関数を提供するパッケージ。どんな言語より最もパワフルでフレキシブルなデータ解析ツールを目指している、志の高いパッケージです。

    pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. It aims to be the fundamental high-level building block for doing practical, real world data analysis in Python. Additionally, it has the broader goal of becoming the most powerful and flexible open source data analysis / manipulation tool available in any language. It is already well on its way toward this goal.

  • Numpy
    Pythonで科学計算するための基本的なパッケージ

  • matplotlib
    データの可視化に用いる最も一般的なパッケージ

  • Jupyter
    コードや式、そこで作図した図や、その説明文を、作ってシェアすることもできるウェブアプリケーション。データ整理や整形、数値計算、統計解析、機械学習など色々出来ます。模索しながらの分析作業や、結果の共有・保管などが楽にできます。

    The Jupyter Notebook is a web application that allows you to create and share documents that contain live code, equations, visualizations and explanatory text. Uses include: data cleaning and transformation, numerical simulation, statistical modeling, machine learning and much more.

  • SciPy
    数学・科学・工学向けのPythonベースのソフトウェア環境のこと。個別のパッケージではなく上記のパッケージ(NumPy, Matplotlib, Jupyter, pandas)を組み合わせたものにSciPy liblraryと呼ばれる科学計算むけの基本となるパッケージを合わせたものの総称。SciPy libraryを指してSciPyということも多い。

蛇足

pandas本家のVisualizationの各種プロットの箇所(Other Plots)より

In addition to these kind s, there are the DataFrame.hist(), and DataFrame.boxplot() methods, which use a separate interface.

kindを使う以外に、DataFrame.hist()とDataFrame.boxplot()は別のインターファイスとして存在する。
よってヒストグラムの書き方は
DataFrame.plot(kind='hist')
DataFrame.plot.hist()
DataFrame.hist()
の3種類あることになります。

30
39
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
30
39