はじめに
pythonのライブラリであるmatoplotlibの使い方を初心者の方向けにまとめます。
matplotlibとは、グラフなどの描画に使うライブラリです。
解決する問題
matplotlibの基本的な使い方がわからないこと
matplotlibの基本的な使い方
import方法
%matplotlib inline
は、jupyter notebookで使用するときに必要なコマンドです。import matplotlib.pyplot as plt
でmatplotlib.pyplot
をpltという名前で呼び出しますと定義します。
%matplotlib inline
import matplotlib.pyplot as plt
線グラフの描画
線グラフを描画するために今回は、sin関数を例に用いて描画します。なので、まずはsin関数を用意します。sin関数は、numpyで用意可能です。x = np.arange(0,10,0.1)
は最小値0、最大値10、刻み0.1の数字を用意するという意味です。y = np.sin(x)
でsin関数にxを代入し、yのリストに格納します。
labelはグラフを描画する際の凡例です。
import numpy as np
x = np.arange(0,10,0.1)
y = np.sin(x)
label = str('sin x')
matplotlibでの描画は頻繁に使うので、独自関数で定義しましょう。plt.plot(x,y,label=label)
は、x
y
の値を代入し、label='凡例名'
でラベリングできます。plt.title("sin x")
でグラフのタイトルplt.xlabel
で、x軸の名前plt.ylabel
で、y軸の名前
def plot(x,y,label):
plt.plot(x,y,label=label)
plt.title("sin x")
plt.xlabel('x')
plt.ylabel('sin x')
plt.legend()
plt.show()
出力結果は以下です。
![](https://tsukimitech.com/wp-content/uploads/2020/11/image-142.png)
ヒストグラム
plt.hist(x)
でヒストグラムを出力可能です。
def hist_plot(x):
plt.title("sin x")
plt.xlabel('hist')
plt.ylabel('num')
plt.hist(x,label='1')
plt.legend()
plt.show()
では、平均0、標準偏差1の乱数でヒストグラムを作成してみましょう。np.random.normal(0,1,1000)
で作成できます。1000は1000点をランダムに作成するという意味です。
x_1 = np.random.normal(0,1,1000)
hist_plot(x_1)
出力結果です。
![](https://tsukimitech.com/wp-content/uploads/2020/11/image-143.png)
二つのヒストグラムをプロットする方法です。plt.hist(x_1,alpha=0.5,label='1')
、plt.hist(x_2,alpha=0.5,label='2')
で二つのヒストグラムのプロットを指示します。alpha=0.5
で透明化することで、グラフの視認性を向上させられます。
def hist_plot(x_1,x_2):
plt.title("hist")
plt.xlabel('hist')
plt.ylabel('num')
plt.hist(x_1,alpha=0.5,label='1')
plt.hist(x_2,alpha=0.5,label='2')
plt.legend()
plt.show()
ではプロットしてみましょう。
x_1 = np.random.normal(0,1,1000)
x_2 = np.random.normal(1,1,1000)
hist_plot(x_1,x_2)
出力結果です。
![](https://tsukimitech.com/wp-content/uploads/2020/11/image-145.png)
散布図
x_1 = np.random.normal(0,1,1000)
、x_2 = np.random.normal(1,1,1000)
で、散布図を作成してみましょう。
x_1 = np.random.normal(0,1,1000)
x_2 = np.random.normal(1,1,1000)
plt.scatter(x)
で散布図を出力可能です。
def scatter_plot(x,y):
plt.title("scatter")
plt.xlabel('x')
plt.ylabel('y')
plt.scatter(x, y)
plt.legend()
plt.show()
出力結果です。
![](https://tsukimitech.com/wp-content/uploads/2020/11/image-146.png)
まとめ
今回の記事は以上です。もし、もっとPythonを勉強したいとお思いの方は、以下の参考書を参考にしてみてください。私の方で、目を通してわかりやすいと感じた本を掲載しています。
コメント