import matplotlib as mpl
import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline
散布図
import numpy as np
import numpy.random as random
random.seed(0)
x = np.random.randn(30)
y = np.sin(x) + np.random.randn(30)
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'o')

plt.figure(figsize=(10, 6))
plt.scatter(x, y)
plt.title('Set title')
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)

連続値
np.random.seed(0)
np_x = np.arange(1000)
np_y_rand = np.random.randn(1000).cumsum()
plt.figure(figsize=(10, 6))
plt.plot(np_x, np_y_rand, label='Label')
plt.legend()
plt.xlabel('X')
plt.ylabel('Y')
plt.grid(True)

グラフ分割
plt.figure(figsize=(20, 6))
plt.subplot(1, 2, 1)
x1 = np.linspace(-10, 10, 100)
plt.plot(x1, np.sin(x1))
plt.subplot(1, 2, 2)
x2 = np.linspace(-10, 10, 100)
plt.plot(x2, np.sin(x2 * 2))
plt.grid(True)

関数グラフ
def example_func(x):
return x**2 + 2*x + 1
x = np.arange(-10, 10)
plt.figure(figsize=(20, 5))
plt.plot(x, example_func(x))
plt.grid(True)

random.seed(0)
plt.figure(figsize=(20, 6))
plt.hist(np.random.randn(10 ** 5) * 10 + 50, bins = 60, range = (20, 80))
plt.grid(True)

?plt.hist
演習問題
def example_func(x):
return 5 * x + 3
x = np.linspace(-10, 10, 100)
plt.figure(figsize=(10, 5))
plt.plot(x, example_func(x))

plt.figure(figsize=(10, 6))
plt.plot(x, np.sin(x), label = 'Sin')
plt.plot(x, np.cos(x), label = 'Cos')
plt.legend()

plt.figure(figsize=(20, 6))
plt.subplot(1, 2, 1)
plt.plot(x, np.sin(x))
plt.subplot(1, 2, 2)
plt.plot(x, np.cos(x))

x1 = np.random.uniform(0.0, 1.0, 1000)
x2 = np.random.uniform(0.0, 1.0, 1000)
plt.figure(figsize=(20, 6))
plt.subplot(1, 2, 1)
plt.hist(x1)
plt.subplot(1, 2, 2)
plt.hist(x2)

その他
np.random.seed(0)
N = 10000
x = np.random.uniform(0.0, 1.0, N)
y = np.random.uniform(0.0, 1.0, N)
import math
cnt = 0
inside_x = []
inside_y = []
outside_x = []
outside_y = []
for n in range(N):
m = math.hypot(x[n], y[n])
if m <= 1.0:
cnt = cnt + 1
inside_x.append(x[n])
inside_y.append(y[n])
else:
outside_x.append(x[n])
outside_y.append(y[n])
cnt
7868
plt.figure(figsize=(10, 10))
plt.scatter(inside_x, inside_y, color = 'g')
plt.scatter(outside_x, outside_y, color = 'r')

print(f'円周率の近似(モンテルカルロ法): { 4.0 * cnt / N }')
円周率の近似(モンテルカルロ法): 3.1472