Skip to content

Instantly share code, notes, and snippets.

@kenta-s
Last active March 21, 2018 05:02
Show Gist options
  • Save kenta-s/acd786ce480522dd4e298457927b707d to your computer and use it in GitHub Desktop.
Save kenta-s/acd786ce480522dd4e298457927b707d to your computer and use it in GitHub Desktop.
matplotlib.pyplotの基本的な使い方

Pyplotの基本的な使い方

ほとんどPyplot公式のチュートリアルそのままの内容なので英語に抵抗がなければ本家を読むことをおすすめします。

https://matplotlib.org/users/pyplot_tutorial.html

x軸

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()

Figure_1.png

x軸が 0.0..3.0になっていることがポイントです。

これは plt.plot([1,2,3,4]) plotにひとつだけリストを与えた場合、matplotlibはそれを y だと判断し、自動的に x を割り出します。 デフォルトのxベクトルはyの長さと同じ長さを持ち、Pythonのrangeは0から始まるため [0,1,2,3] となります。

plot()が受け取る引数

xを明示したい場合は

plt.plot([1, 2, 3, 4], [1, 4, 9, 16])

と、x,yリストをペアで渡します。 plot()はこのx,yのペアをいくつでも引数に受け取ることができます。

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], [1, 3, 5, 7], [2, 6, 10, 14])
plt.show()

Figure_2.png

以下のように、plot()を複数行にわけて書くこともできます。 無理に一行で書くよりもこちらのほうが読みやすいかもしれません。

import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
plt.plot([1, 3, 5, 7], [2, 6, 10, 14])
plt.show()

それぞれのx,yペアは、プロットの色とラインタイプを指定する3つ目のオプション引数を受け取ることもできます。 例えば、赤い円にしたい場合は 'ro' という文字列を渡します。 rはred, oは... oっぽい形状、とでもいいましょうか。つまり円です。

import matplotlib.pyplot as plt
plt.plot([1,2,3,4], [1,4,9,16], 'ro')
plt.axis([0, 6, 0, 20])
plt.show()

Figure_3.png

使える色とラインタイプは以下リンクの一覧から https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.plot

axis()は軸を指定するもので[xmin, xmax, ymin, ymax]の順番で指定します。

もちろんNumPyにも対応しています。 実は、これまで挙げた例でも内部的にはnumpy arrayに変換されています。

複数のラインをそれぞれ異なるスタイルで一行でプロットする例です。

import numpy as np
import matplotlib.pyplot as plt

# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# 赤のダッシュ, 青の正方形, 緑の三角形
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Figure_4.png

Controlling line properties

Linesにはいくつかの属性をセットすることができます。 line propertiesのセットにはいくつかの方法があります。

Use keyword args:

plt.plot(x, y, linewidth=2.0)

Use the setter methods of a Line2D instance.

line, = plt.plot(x, y, '-')
line.set_antialiased(False) # turn off antialising

Use the setp() command

lines = plt.plot(x1, y1, x2, y2)
# use keyword args
plt.setp(lines, color='r', linewidth=2.0)
# or MATLAB style string value pairs
plt.setp(lines, 'color', 'r', 'linewidth', 2.0)

Working with multiple figures and axes

pending

Working with text

pending

Logarithmic and other nonlinear axes

pending

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment