Matplotlibの使い方をみてみよう!⑦

こんにちは! EMです^^

 

さっそく、みなさんの2021年の抱負はありますか?

2020年以上に邁進していきたい!という方は多いんじゃないでしょうか。

 

私は昨日1年の抱負をいくつか考えていたんですが(年明けてから考えてます笑)

「1つは好きな時間に触れる時間を多くする」という事です。

 

この機械学習も私の好奇心の追及の一環としてはじめましたが

自分が何が好きなのかをはっきり自覚する事はとても大切だと思っています。

聞くと当たり前の事だと感じますが、今まではフィーリングとか

ぼやっと「これいいな~」くらいで、はっきりと自覚していない事が多かったんですよね。

でも好きな事との接触時間が長ければ長いほど、単純にハッピーになれる時間が

増えるという事なので、少しでも好きな事と積極的に関われる1年にしていきたい

と思っています^^

 

そしてこのブログを見て下さるみなさんも、機械学習やテクノロジーが

「好き」とか「興味がある」事のひとつだといいなと思う今日この頃です。

 

 

さて、いつも以上に前置きが長くなりましたが、本題に入りたいと思います。

先日はMatplotlibの応用を深堀していきましたね。

 

日付の書式設定(Date Formatting)

 timeseries_1.csv のデータセットをもう一度読み込み
日付の書式設定を行ってみましょう。

 

df2 = pd.read_csv('timeseries_1.csv',index_col=0,parse_dates=True)
df2.head()
 
high列とlow列をプロットしてみます。
 
fig = plt.figure()
plt.plot(df2.index,df2['high'],label='High', color='red')
plt.plot(df2.index,df2['low'],label='Low', color='blue')
plt.xlabel('Time', size=15)
plt.ylabel('Price',size=15)
plt.legend()
plt.xlim(df2.index[0],df2.index[-1])
plt.title('Futures Prices',size=18)
plt.grid()
plt.show()
 
 
Matplotlibは、軸ラベルの情報をまとめて、不要なものをすべて削除しようとします。
今回の場合、すべての価格は同じ日に起こっているため、時刻のみが表示されます。
日付時刻を少し斜めに傾けると、軸ラベルとして読みやすくなることがよくあります。
これは、コマンドfig.autofmt_xdate()を使って実行できます。
このコマンドは、x軸ラベルとして表示される日時を自動的にフォーマットします。
 
fig = plt.figure()
plt.plot(df2.index,df2['high'],label='High', color='red')
plt.plot(df2.index,df2['low'],label='Low', color='blue')
plt.xlabel('Time', size=15)
plt.ylabel('Price',size=15)
plt.legend()
plt.title('Futures Prices',size=18)
plt.grid()
fig.autofmt_xdate()
plt.show()
 
 
他の例として、時間の代わりに日付を使用していきましょう。
 
df3 = pd.DataFrame({'Temperature':np.random.randint(10,32,30)},
   index=pd.date_range('2016-06-01',periods=30,freq='12H'))
 
 
fig = plt.figure()
plt.plot(df3.index,df3['Temperature'],label='Temp')
plt.xlabel('Time', size=15)
plt.ylabel('Temperature',size=15)
plt.legend()
plt.title('Temperatures on a 12 Hour Scale',size=18)
plt.grid()
plt.tick_params(axis='x', labelsize=10)
plt.xlim(df3.index[0],df3.index[-1])
fig.autofmt_xdate()
plt.show()
 
 
フォントサイズの目盛りラベルを大きくして、日付を水平のままにするのと比較してみましょう。
 
fig = plt.figure()
plt.plot(df3.index,df3['Temperature'],label='Temp')
plt.xlabel('Time', size=15)
plt.ylabel('Temperature',size=15)
plt.legend()
plt.title('Temperatures on a 12 Hour Scale',size=18)
plt.grid()
plt.tick_params(axis='x', labelsize=10)
plt.xlim(df3.index[0],df3.index[-1])
plt.tick_params(axis='x', labelsize=15)
#fig.autofmt_xdate()
plt.show()
 
 

マーカー(Markers)

For broken-line graphs, like we've been seeing, we can emphasize our actual data points by placing markers at their locations. A few common markers are (".",point),(",",pixel),("o",circle), and ("D",diamond). Alternatively, we can specify the linestyle as .- which gives a solid line graph with dots:

これまで見てきたような折れ線グラフの場合、マーカーをその場所に配置することで
実際のデータポイントを強調する事ができます。

いくつかの一般的なマーカーはこんな感じです↓

(".",point),(",",pixel),("o",circle), ("D",diamond)

または線種を.-として指定することもできます。
これにより、ドットで出来た実線グラフをつくる事が出来ます。

 

fig = plt.figure()
plt.plot(df1.index,df1['A'],'.-',label='Stock A', color='red',linewidth=1.4)
plt.plot(df1.index,df1['B'],label='Stock B',marker='o' ,color='green',linewidth=0.5)
plt.plot(df1.index,df1['C'],label='Stock C',marker='D', color='blue',linewidth=2)
plt.plot(df1.index,0*df1.index,color='black')
plt.xlabel('Days After First Trade', size=10)
plt.ylabel('Price',size=12)
plt.legend()
plt.title('Stock Prices',size=18)
plt.grid(b=True)
plt.xlim(0,49)
plt.show()
 
マーカーについて詳しく知りたい方は、ぜひmatplotlibの公式ページも見てみて下さい。
 
 

 

グラフ関数(Graphing Functions)

 

グラフ関数これまで見てきた例では、離散データセット(個別のデータセット)をグラフ化しています。

 

さて、ここで問題です。

もしsin(x)やe−x2などの連続関数が出てきたとき、どのようにグラフ化するでしょうか?

 

その答えは、x軸として細かい点をたくさん使い、一連のデータポイントを作っていく事です。
ポイント間を線で埋める事で、目に見えないくらい十分に細かい点と点の繋がりから
一連のグラフを作り事ができます。

これを実際に行うために、np.arange()関数を使用します。
(注:これは配置ではなく、範囲です)
この関数は、np.arange(start,end,step)という構文を使用して
均等なスペースポイントの連続をつくります。

 

 

np.arange(0,10,0.5)
 
t = np.arange(0.01.0+0.010.01)
s = np.sin(2*np.pi * t)
plt.plot(t, s)
plt.show()
 
 
 
ステップサイズを0.01から0.1に変更するとどうなるでしょうか?
また、先ほどグラフを調整した方法を使えば
数学の教科書に出てきそうなグラフのように見せることもできます。
 
t = np.arange(0.01.0+0.010.01)
s = np.sin(2*np.pi * t)
plt.plot(t, s)
plt.plot(t,0*t,color='black')
plt.xlim(0,1)
plt.grid()
plt.show()
 
 
大まかにグラフを滑らかに見せるため、0.01にステップサイズを保つといいでしょう。
 
 
t = np.arange(1.0100.0+11)
l = np.log(t/2)
plt.plot(np.log(t))
plt.show()
 
 
0.1のサイズともぜひ比べてみて下さい。
 
 
t = np.arange(1.0100.0+0.10.1)
l = np.log(t/2)
plt.plot(np.log(t))
plt.show()
 
These tools will allow us to graph both data sets and mathematical functions on the same graph, which will be a good way to visually inspect any models we create.
 
これらのツールを使用すると、データセットと数学関数の両方を同じグラフに示す事ができます。
これは、作成したモデルを視覚的に考察する上で便利で分かりやすい方法です。
 

ファイルの出力

 

プロジェクトの様々な場面で使用するため、作成したグラフをファイルに書き込むことができます。
これを行うにはplt.show()をコマンドplt.savefig('filepath')に置き換えます。
1つ注意しておく事は、生成される画像ファイルのデフォルトサイズはかなり小さいのですが
dpiを設定することでコントロールできるという事です。
デフォルトと先程の例で調整した出力結果を比較してみましょう。

 

fig = plt.figure()
plt.plot(df3.index,df3['Temperature'],label='Temp')
plt.xlabel('Time', size=15)
plt.ylabel('Temperature',size=15)
plt.legend()
plt.title('Temperatures on a 12 Hour Scale',size=18)
plt.grid()
plt.tick_params(axis='x', labelsize=10)
plt.xlim(df3.index[0],df3.index[-1])
plt.tick_params(axis='x', labelsize=15)
fig.autofmt_xdate()
plt.savefig('c:\\users\\Patrick\\default_dpi.png')

my_dpi=96
plt.savefig('c:\\users\\Patrick\\adjusted_dpi.png',dpi=my_dpi*2)
 

デフォルトの解像度は864x720ですが、調整済みの解像度は2304x1920です。 

 

サブプロット(Subplots)

Matplotlibの素敵な機能の1つとして、同じ画像に複数のグラフを出力できることです。
これはgridspecを使用してサブプロットを作成することで可能になります。
まずGridSpec(rows,columns)を使用してサブプロットのサイズを宣言し
下記の様にplt.subplot2grid()を使用して個々のデータをプロットします。

 

GridSpec(number of rows, number of columns)
plt.subplot2grid((grid rows, grid columns),
          (plot row position, plot column position))

plt.plot(x,y)

 

df2(冒頭に定義しています)からhighとlow列の両方をプロットします。
その為2つの行と1つの列があり、位置が(0,0)と(1,0)になります。(0から数える)

 

import matplotlib.gridspec as gridspec

fig = plt.figure()
# set up subplot grid; 行と列がいくつあるか設定する
gridspec.GridSpec(2,1)

plt.subplot2grid*1# (2,1) = 合計のplotサイズ, (0,0)=このプロットが指定される
plt.plot(df2.index,df2['high'],label='High', color='red')
plt.xlabel('Time', size=12)
plt.ylabel('Price',size=12)
plt.legend()
plt.xlim(df2.index[0],df2.index[-1])
plt.title('Futures Prices',size=18)
plt.grid()
fig.autofmt_xdate()

plt.subplot2grid*2
plt.plot(df2.index,df2['low'],label='Low', color='blue')
plt.xlabel('Time', size=12)
plt.ylabel('Price',size=12)
plt.legend()
plt.xlim(df2.index[0],df2.index[-1])
plt.grid()
fig.autofmt_xdate()

plt.show()

 

 We can even make more complicated arrangements by stretching graphs over multiple columns. We'll make a subplot of the volume, open, and close prices; the volume will by 2x2 rows and columns, and each of the open and close will be 1x1 underneath. We stretch by
 
グラフを複数の列に拡大することで、さらに複雑な操作を行うこともできます。
ボリューム、始値、終値のサブプロットを作成します。
ボリュームは2x2の行と列で、始値、終値はそれぞれ1x1以下になります。
↓このコードによって拡大する事が出来ます。
plt.subplot2grid((r1,c1),(px,py),colspan=n,rowspan=m):
 
 
gridspec.GridSpec(3,2)

# 3rows, 2columns.  
#The volume will be at position (0,0) and will span 2 rows and 2 columns.  
#The open and close 
will be at positions (2,0) and (2,1), and will be normal sized.
plt.subplot2grid*3
plt.plot(df2.index,df2['open'],label='Open', color='red')
plt.xlabel('Time', size=12)
plt.ylabel('Price',size=12)
plt.legend()
plt.xlim(df2.index[0],df2.index[-1])
plt.grid()
fig.autofmt_xdate()

plt.subplot2grid*4
plt.plot(df2.index,df2['close'],label='Close', color='blue')
plt.xlabel('Time', size=12)
plt.ylabel('Price',size=12)
plt.legend()
plt.xlim(df2.index[0],df2.index[-1])
plt.grid()
fig.autofmt_xdate()

plt.show()
 
 
 
あえて今回はコードのみに留めます^^
 
長々となりましたが、ぜひ上記のコードを参考にしてみてくださいね。
 

ちなみに皆様に朗報です!

私今まで知らなかったんですが、CodeCampさんが無料で5回分無料レッスンを

されているらしいです、、、!

私が他のオンラインスクールで機械学習のコースを受講した際は

グループレッスンで約2倍のお値段を払ったので

完全マンツーマンでこのお値段は超良心的だなと思います。。。

 

 

 

ぜひ気になる方は無料体験もされてるみたいなので、一度WEBサイトを見てみてくださいね。

データ分析は時代が変化しても、必ず重宝される分野だと思いますし
デザイナーやWEBデベロッパー用などのコースも幅広くあるようなので
興味があるコースをチラ見してはいかがでしょうか^^

もちろん、個人で勉強する事もできますが、挫折経験のある私の個人的な経験から
プロから基礎を学ぶのは、本当に超効率的な自己投資だと思います。

 
 
それでは最後までよんで頂きありがとうございました!

*1:2,1), (0,0

*2:2,1), (1,0

*3:3,2), (0,0),colspan=2,rowspan=2)

plt.plot(df2.index,df2['volume'],label='Vol', color='green')
plt.xlabel('Time', size=12)
plt.ylabel('Qty',size=12)
plt.legend()
plt.xlim(df2.index[0],df2.index[-1])
plt.title('Futures Prices',size=18)
plt.grid()

plt.subplot2grid((3,2), (2,0

*4:3,2), (2,1