これまでいくつかの記事でグラフ中に残差を表現するための線を引いてきた。
これどうやっていたかというと、こんな感じで残差を引く用のデータを作成して一個ずつプロットする、という方法をとっていた。
def return_residue_plot(np_data_x, data_y, b, a): exp_y = np_data_x * b + a xx = [] yy = [] for n in range(0, len(np_data_x)): xx.append([np_data_x[n], np_data_x[n]]) yy.append([exp_y[n], data_y[n]]) return xx, yy xx1, yy1= return_residue_plot(x, y, b, a) for n in range(0,len(x)): ax1.plot(xx1[n], yy1[n], color="#cd0000", linewidth=4, zorder=1)
しかし世の中にはstem plotという便利なものがあるらしい。
import matplotlib.pyplot as plt x = [1,2,3,4,5] bottom = 3 fig, ax = plt.subplots() ax.stem(x, bottom=bottom) fig.show()
見事に残差が表現できている。まじか。
stemの解説
設定はシンプルでxとyをリストで指定すると散布図で点が打たれ、bottomからの線が引かれる。本当は'vertical', 'horizontal'という設定もあるのだけれど、なぜか私の環境でできなかったので今回はスキップ。
matplotlib.pyplot.stem(x, y, bottom=bottom)
stemの簡易スタイル設定
stemプロットは色々とスタイルを変更することが出来る。
こちらは簡易的なスタイル設定。同じ関数中でそれぞれの色を設定できるので便利なのだが、太さなどは指定することが出来ない。
matplotlib.pyplot.stem( x, y, bottom=bottom, markerfmt=('h', '--', 'g'), basefmt=(':', 'r'), linefmt=('s','-','b'), )
stemのスタイル設定
線の太さのように色々設定したいよ、という場合はいったん変数に入れてからsetで変えることが出来る。
stemlinesに関してはリスト形式で格納されていてfor文で回す必要があった。これも他のサイトの情報と挙動が違うのだけど何なんでしょう?バージョンがおかしいのか?
markerline, stemlines, baseline = plt.stem(x, y, bottom=bottom) markerline.set( markersize=5, marker='s', color='green', linestyle='--', linewidth=1 ) for n in stemlines: n.set( markersize=10, marker='s', color='blue', linestyle='-', linewidth=3 ) baseline.set( markersize=0, marker='s', color='red', linestyle=':', linewidth=1 )
これで定数からの残差は表現できるが、bottomは定数のみでリストに対応しておらうず、回帰直線からの残差は表現できない。
なので次回はbottomを変数にする取り組み。
どんなパラメーターが実施可能かは下記サイトが大変参考になりました。