- 最基本的线性回归图
matplotlib库里的pyplot类似于matlab的功能, 可以plot任何曲线。可以加x轴, y轴标记。默认x轴从0开始。
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4]) # y = [1, 2, 3, 4]
plt.ylabel('some numbers') # add y axis
plt.xlabel('x axis') # x = [0, 1, 2, 3] by default
plt.show()
- 如果规定x轴, y轴:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16])
- plot 格式化:
plt.plot([1, 2, 3, 4], [1, 4, 9, 16], 'ro') # ro: red dot
plt.axis([0, 6, 0, 20]) # domain of x, y
plt.show()
- 一般情况下matplotlib.pyplot 与numpy 一起使用:得到多条曲线
import numpy as np
# evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)
# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()
- 作图:多种参数
通过字典
data = {'a': np.arange(50),
'c': np.random.randint(0, 50, 50),
'd': np.random.randn(50)}
data['b'] = data['a'] + 10 * np.random.randn(50)
data['d'] = np.abs(data['d']) * 100
plt.scatter('a', 'b', c='c', s='d', data=data)
plt.xlabel('entry a')
plt.ylabel('entry b')
plt.show()
- 多种类型图:
names = ['group_a', 'group_b', 'group_c']
values = [1, 10, 100]
plt.figure(figsize=(9, 3)) # width, height
plt.subplot(131)
plt.bar(names, values)
plt.subplot(132)
plt.scatter(names, values)
plt.subplot(133)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.show()
- 函数:
def f(t):
return np.exp(-t) * np.cos(2*np.pi*t)
t1 = np.arange(0.0, 5.0, 0.1)
t2 = np.arange(0.0, 5.0, 0.02)
plt.figure()
plt.subplot(211) # first figure
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k') # blue dot
plt.subplot(212) # second figure
plt.plot(t2, np.cos(2*np.pi*t2), 'r--') # red dash
plt.show()