[3-1] NumPyのモジュールをインポートします。
In [1]:
import numpy as np
import matplotlib.pyplot as plt
[3-2] xのn乗を計算する関数を定義します。
In [2]:
def power(x, n):
y = x ** n
return y
[3-3] -10〜10を100個に分割したxに対して、xの2乗を計算します。
In [3]:
xs = np.linspace(-10,10,100)
ys = power(xs, 2)
[3-4] xの2乗のグラフを描きます。
In [4]:
fig = plt.figure(figsize=(3,3))
subplot = fig.add_subplot(1,1,1)
subplot.set_xlim(-10,10)
subplot.set_ylim(0,100)
subplot.plot(xs, ys)
Out[4]:
[3-5] xの1乗〜xの4乗のグラフをまとめて描きます。
In [5]:
fig = plt.figure(figsize=(5,5))
subplot = fig.add_subplot(1,1,1)
subplot.set_xlim(-10,10)
subplot.set_ylim(-100,100)
for i in range(1, 5):
xs = np.linspace(-10,10,100)
ys = power(xs, i)
subplot.plot(xs, ys, label=('x ** %d' % i))
subplot.legend(loc='lower right')
Out[5]:
[3-6] 2種類の三角関数を別々のグラフに描きます。
In [6]:
xs = np.linspace(0,2*np.pi,100)
fig = plt.figure(figsize=(6,6))
subplot = fig.add_subplot(2,1,1)
subplot.set_xlim(0, 2*np.pi)
subplot.set_ylim(-1,1)
subplot.plot(xs, np.sin(xs), label='sin (2*pi*x)')
subplot.legend(loc='best')
subplot = fig.add_subplot(2,1,2)
subplot.set_xlim(0, 2*np.pi)
subplot.set_ylim(-1,1)
subplot.plot(xs, np.cos(xs), label='cos (2*pi*x)')
subplot.legend(loc='best')
Out[6]: