ライブラリの読み込み
jupyter notebookを開き、基本的なデータ分析に必要なnumpy・pandasを読み込みます。jupyter内でグラフを表示するために「%matplotlib inline」の表記が必要なので忘れずに記載しておきましょう。seabornは必須ではありませんが、読み込んでおくとそれだけでグラフがリッチ?な感じになります。seabornは独自の機能があるのですが、今回はmatplotlibの表記に統一します。また、グラフ内で日本語を使えるようにフォントの指定もしておきましょう。
% matplotlib inline
import numpy as np
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
plt . rcParams [ 'font.family' ] = 'IPAPGothic'
plt . rcParams [ 'font.size' ] = 12
グラフのベースの描画
まず、グラフのベースを描画してみます。かなり多彩な設定が可能なので、できるだけ多くの設定が表現できるようにコードを書いてみました。表現できなかった部分はググってみてください。公式サイトに他のパラメータも載っているので、下記と同じように引数で指定すれば簡単に実現できます。
plt . figure ( figsize = ( 12 , 5 )) #グラフベースを描画しサイズを指定
plt . title ( "多彩なビジュアル表現" , fontsize = 17 ) #グラフのタイトルを設定
plt . plot ([ 0 , 1 , 2 , 3 , 4 ], [ 0 , 2 , 4 , 6 , 8 ], 'b-o' , label = 'ライン1' , linewidth = 3 ) #後ほど説明
plt . plot ([ 0 , 1 , 2 , 3 , 4 ], [ 0 , 1 , 1.5 , 2 , 5 ], 'r--^' , label = 'ライン2' , linewidth = 5 ) #後ほど説明
plt . axis ([ 0 , 3.5 , 0 , 6.5 ]) #グラフの軸範囲を設定
plt . xticks ( np . arange ( 0 , 4 , step = 0.2 )) #グラフのX軸目盛サイズを設定
plt . yticks ( np . arange ( 0 , 6.5 , step = 0.5 )) #グラフのY軸目盛サイズを設定
plt . xlabel ( 'x ラベル' , fontsize = 12 ) #グラフのX軸ラベルを設定
plt . ylabel ( 'y ラベル' , fontsize = 12 ) #グラフのY軸ラベルを設定
plt . legend ( bbox_to_anchor = ( 0.5 , - 0.2 ), loc = "center" ) #グラフの凡例を設定
figure
グラフを描画します。サイズ・色などの細かい指定ができますが、今回は一番使うであろうsizeの変更をしてみました。
title
名前通りタイトルを表示します。文字のサイズ・位置の指定もできます。
axis
軸の範囲指定をします。[x最小,x最大,y最小,y最大]の順で入力すると、その範囲のグラフが描画されます。
xticks・yticks
軸の目盛の間隔や、どの位置で表示させるか自由に表現することができます。
xlabel・ylabel
軸のラベル(どういった数量を表しているか)を表記することができます。
legend
凡例を表記できます。引数locに以下のパラメータを入力すれば、凡例の位置を変更することが可能です。また、どうしてもグラフ線とかぶってしまう場合、枠外にもって行くことも可能です。引数bbox_to_anchorで位置をうまい具合に調整しましょう。
文字による指定 コードによる指定 best 0 upper right 1 upper left 2 lower left 3 lower right 4 right 5 center left 6 center right 7 lower center 8 upper center 9 center 10
subplot
複数のグラフを表示し比較することが可能です。
plt . figure ( figsize = ( 12 , 8 ))
plt . subplot ( 231 ) #1桁目 -- グラフの行数、2桁目 -- グラフの列数、3桁目 -- グラフの番号、subplot(2,3,1)の記載でも良い。
plt . title ( "多彩なビジュアル表現1" )
plt . plot ([ 0 , 1 , 2 , 3 , 4 ],[ 0 , 2 , 4 , 6 , 8 ], 'b-o' , label = 'ライン1' )
plt . xlabel ( 'x ラベル' )
plt . ylabel ( 'y ラベル' )
plt . legend ()
plt . subplot ( 232 , sharey = plt . subplot ( 231 )) #引数sharex・shareyで軸を指定のグラフと同じにできる。
plt . title ( "多彩なビジュアル表現2" )
plt . plot ([ 0 , 1 , 2 , 3 , 4 ],[ 0 , 1 , 1.5 , 2 , 5 ], 'r--^' , label = 'ライン2' )
plt . xlabel ( 'x ラベル' )
plt . ylabel ( 'y ラベル' )
plt . legend ()
plt . tight_layout ()
plt . subplot ( 233 , sharey = plt . subplot ( 231 ))
plt . title ( "多彩なビジュアル表現3" )
plt . plot ([ 0 , 1 , 2 , 3 , 4 ],[ 0 , 0.1 , 0.2 , 0.3 , 0.4 ], 'g:d' , label = 'ライン3' )
plt . xlabel ( 'x ラベル' )
plt . ylabel ( 'y ラベル' )
plt . legend ()
plt . subplot ( 234 , sharey = plt . subplot ( 231 ))
plt . title ( "多彩なビジュアル表現4" )
plt . scatter ([ 0 , 1 , 2 , 3 , 4 ], [ 5 , 8 , 7 , 0 , 10 ], label = '散布図4' )
plt . xlabel ( 'x ラベル' )
plt . ylabel ( 'y ラベル' )
plt . legend ()
plt . subplot ( 235 , sharey = plt . subplot ( 231 ))
plt . title ( "多彩なビジュアル表現5" )
plt . bar ([ 0 , 1 , 2 , 3 , 4 ],[ 0 , 2 , 4 , 6 , 8 ], label = '棒グラフ5' )
plt . xlabel ( 'x ラベル' )
plt . ylabel ( 'y ラベル' )
plt . legend ()
plt . subplot ( 236 , sharey = plt . subplot ( 231 ))
plt . title ( "多彩なビジュアル表現6" )
plt . plot ([ 0 , 1 , 2 , 3 , 4 ],[ 0 , 2 , 4 , 6 , 8 ], 'b-o' , label = 'ライン6' )
plt . xlabel ( 'x ラベル' )
plt . ylabel ( 'y ラベル' )
plt . legend ()
plt . tight_layout () #文字がかぶらないようにする。
折れ線グラフの描画(plot)
主に時系列のデータの変化を比較する際に使用されます。
import datetime
import matplotlib . dates as mdates
#時系列をmatplotlibで扱う
fig , ax = plt . subplots ()
ax . xaxis . set_major_locator ( mdates . DayLocator ()) #x軸の単位を指定
ax . xaxis . set_major_formatter ( mdates . DateFormatter ( '%Y-%m- %d ' )) #x軸の表記を指定
#お試しデータの作成
x = pd . to_datetime ([ '20180101' , '20180102' , '20180103' , '20180104' , '20180105' ])
y1_name = 'りんご'
y1 = [ 100 , 300 , 200 , 500 , 600 ]
y2_name = 'みかん'
y2 = [ 10 , 100 , 500 , 800 , 1500 ]
#お試しデータをpandas dataframeに格納
df_sales = pd . DataFrame ({ '日付' : x , y1_name : y1 , y2_name : y2 })
df_sales . set_index ( '日付' , inplace = True )
#折れ線グラフを描画
plt . plot ( df_sales . index , df_sales [ y1_name ] , 'b-o' , label = y1_name )
plt . plot ( df_sales . index , df_sales [ y2_name ] , 'y--^' , label = y2_name )
#グラフのその他設定
plt . title ( "折れ線グラフ" , fontsize = 17 )
plt . xlabel ( '日付' , fontsize = 12 )
plt . ylabel ( '販売数' , fontsize = 12 )
plt . legend ( bbox_to_anchor = ( 0.5 , - 0.2 ), loc = "center" )
棒グラフの描画(bar)
主に数量や大きさを比較するのに使用されます。
plt . figure ()
#棒グラフを描画
plt . bar ([ 0 , 1 , 2 ], [ 1000 , 1500 , 800 ], tick_label = [ 'りんご' , 'みかん' , 'いちご' ], align = "center" )
#グラフのその他設定
plt . title ( "棒グラフ" , fontsize = 17 )
plt . xlabel ( '商品名' , fontsize = 12 )
plt . ylabel ( '販売数' , fontsize = 12 )
ヒストグラムの描画(hist)
主にデータの分布をみるのに使用されます。
plt . figure ()
#ヒストグラムを描画
plt . hist ( np . random . normal ( 60 , 8 , 10000 ), bins = 15 , facecolor = 'g' )
#グラフのその他設定
plt . title ( "ヒストグラム" , fontsize = 17 )
plt . xlabel ( '点数' , fontsize = 12 )
plt . ylabel ( '人数' , fontsize = 12 )
散布図の描画(scatter)
主に2つの項目の相関関係をみるのに使用されます。今回は傾向を把握しやすいよう単回帰直線も加えました。
from sklearn import linear_model
clf = linear_model . LinearRegression ()
#データの学習
X = pd . DataFrame ({ 'x科目' : np . random . normal ( 60 , 8 , 100 )})
Y = pd . DataFrame ({ 'y科目' : np . random . normal ( 40 , 5 , 100 )})
clf . fit ( X , Y )
# 係数
a = clf . coef_
# 切片
b = clf . intercept_
#分布図を描画
plt . scatter ( X , Y , c = 'gray' , alpha = 0.5 )
#単回帰直線をグラフ化
#predict 計算式: 係数 * X +切片
plt . plot ( X , clf . predict ( X ), 'r' )
#グラフのその他設定
plt . ylabel ( 'y科目' )
plt . xlabel ( 'x科目' )
plt . title ( '分布図と単回帰直線グラフ' )
plt . figure ()