Matplotlibの使い方

機械学習の結果を表現するのにいろいろな二次元のグラフを使うのが便利なので, 起勉強しながら記事にしてみました.

Matplotlibの描き方

描画は以下の順に行います.

  1. figure関数でFigureオブジェクトを作成
  2. FigureオブジェクトからAxesオブジェクトを作成
  3. Axesオブジェクトからデータをプロット
  4. 実際に描写

本当に簡単なコードにしてみました.

import matplotlib.pyplot as plt
plt.style.use("ggplot")

##### 1. figure関数でFigureオブジェクトを作成
fig = plt.figure()
print(type(fig))

##### 2. FigureオブジェクトからAxesオブジェクトを作成
ax = fig.add_subplot(111)
print(type(ax))

##### 3. Axesオブジェクトからデータをプロット
ax.plot([0,1,2],[0,2,4])

### 実際に描写
plt.show()

出力はこんな形です.

<class 'matplotlib.figure.Figure'>
<class 'matplotlib.axes._subplots.AxesSubplot'>

f:id:padic-aririri:20180413215639p:plain

plotの入力はArrayクラス,numpy.ndarray,pandas.Seriesクラス等が受け取れます. これで最低限書き方のイメージはつかめました. とはいえグラフはこれだけでは終わりません.

グラフを作る時考えるのは - データ以外をどうするとすぐわかるか - 何グラフで描画するか かなと思います.

これらについての設定方法を説明しておきます.

グラフの種類

  • 散布図
  • 折れ線
  • 箱ひげ図
  • ヒストグラム
  • 円グラフ

先程はplotでしたが,これらの図に合わせて使うメソッドが違います

関数 図の種類
scatter() 散布図
plot() 折れ線
boxplot() 箱ひげ図
hist() ヒストグラム
pie() 円グラフ

メソッドの詳細は公式ページやここをみるとわかりやすいと思います.

データ以外の作成方法

グラフの見た目を改善するということで思い浮かんだのは以下でした.

  • 文字
  • 軸の名前
  • タイトル

これらについて具体的に説明します.

文字
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(331)
ax2 = fig.add_subplot(332)
ax3 = fig.add_subplot(333)

for i ,ax in enumerate([ax1,ax2,ax3],start = 1):
    txt = "ax{0}\n(33{0})".format(i)
    ax.text(0.2,0.4,txt,fontsize=12)
plt.show()

f:id:padic-aririri:20180413215855p:plain

軸の名前

軸を設定するにはset_xlabel.set_ylabelを使えばできます.,

import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot([1,4,3],[0,1,4],label="sample")
ax.set_xlabel("x-layer")
ax.set_ylabel("y-layer")
plt.show()

f:id:padic-aririri:20180413220818p:plain

グラフ/線のタイトル

グラフのタイトルはplt.title()で設定できます. 線のタイトルはplot()の引数にlabel=として設定してできます. ax.legend()をすることでラベルが具体的に見えます.

plt.style.use("ggplot")
fig = plt.figure()
ax = fig.add_subplot(122)
x = np.linspace(0,2.0,100)
y = np.exp(x)
z = np.sin(x * np.pi )

ax.plot(x,y,label="exp")
ax.set_xlabel("x-layer")
ax.set_ylabel("y-layer") 
ax.plot(x,z,label="sin")
ax.set_title("Graph Title")
ax.legend()
bx = fig.add_subplot(121)
bx.hist(y,label="sinhist",bins=20)
bx.set_title("hist")
plt.show()

f:id:padic-aririri:20180413222535p:plain

基本編は以上です. 複雑なことはこれから鍛えていこうと思います.

// コードブロック