LoginSignup
5
2

More than 5 years have passed since last update.

Matplotlibの使い方

Last updated at Posted at 2017-02-05

準備

plot_figure.py
import numpy as np
import matplotlib.pyplot as plt

plot関数

平面の折れ線グラフや散布図に使う

折れ線グラフ

plot_figure.py
x = np.arange(-3,3,0.1)
y = np.sin(x)
plt.plot(x,y)
plt.show()

=> x=-3,3,0.1の時のsinの値をグラフ化
plt1.png

  • np.arangeはx軸になる数字の列を作成するもの
  • plot関数の第一引数がx軸、第二引数がy軸になる
  • show()でグラフを描写

散布図

plot_figure.py
x = np.random.randint(0,10,30)
y = np.sin(x) + np.random.randint(0,10,30)
plt.plot(x,y,"o")
plt.show()

plt2.png

  • plot()の第三引数の"o"は小さい円マーカー
  • "ro"で赤(red)のマーカーにすることもできる

hist関数

ヒストグラムを描写する

plot_fugure.py
plt.hist(np.random.randn(1000))
plt.show()

plt3.png

タイトル => title関数

plot_figure.py
plt.hist(np.random.randn(1000))
plt.title("Histgram")
plt.show()

plt4.png

y軸の範囲 => ylim関数

plot_figure.py
x = np.arange(0,10,0.1)
y = np.exp(x)
plt.plot(x,y)
plt.title("exponential function $ y = e^x $")
plt.ylim(0,5000) # y軸を0~5000の範囲に指定
plt.show()

plt5.png

破線を引く => hlines関数

複数のグラフを同じ領域に描写するには、単純に2度呼び出せば良い
y=-1,y=1の直線をhlines関数で描写する

plot_figure.py
xmin, xmax = -np.pi, np.pi
x = np.arange(xmin, xmax, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)
plt.plot(x, y_sin)
plt.plot(x, y_cos)
plt.hlines([-1, 1], xmin, xmax, linestyles="dashed")  # y=-1, 1に破線を描画
plt.title(r"$\sin(x)$ and $\cos(x)$")
plt.xlim(xmin, xmax)
plt.ylim(-1.3, 1.3)
plt.show()

plt6.png

別々のグラフを1つの図に描写する => subplot関数

1つの図に収めたいプロットの行数、列数、プロットの番号を指定

plt.subplot(行数、列数、プロットの番号)

先ほどの図の2つの関数を上下に分割してみる
上下に分割するので行数は2となる
列数は1

plot_figure.py
xmin, xmax = -np.pi, np.pi
x = np.arange(xmin, xmax, 0.1)
y_sin = np.sin(x)
y_cos = np.cos(x)

# sinのプロット
plt.subplot(2,1,1)
plt.plot(x,y_sin)
plt.title(r"$\sin x$")
plt.xlim(xmin,xmax)
plt.ylim(-1.3,1.3)

# cosのプロット
plt.subplot(2,1,2)
plt.plot(x,y_cos)
plt.title(r"$\cos x$")
plt.xlim(xmin,xmax)
plt.ylim(-1.3,1.3)

plt.tight_layout() # タイトルの被りを防ぐ
plt.show()

plt7.png

  • subplot(2,1,1)の代わりにsubplot(221)と書くこともできる

参考

matplotlib入門を参考に勉強させていただきました。

5
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
2