x = np.linspace(0, 2, 100)
# label 表示图例文字,比较方便
plt.plot(x, x, label='linear')
plt.plot(x, x**2, label='quadratic')
plt.plot(x, x**3, label='cubic')
plt.xlabel('x label')
plt.ylabel('y label')
plt.title("Simple Plot")
# 添加图例
plt.legend()
plt.show()
import numpy as np
t = np.arange(0., 5., 0.2)
# 设置颜色、记号、线形的方法相同
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
# 同样有 scatter 等画图方法
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))
# subplot 可以是三位数,就是省略了之间的逗号
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()
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 5, 20)
y = np.sin(x)
z = np.cos(x)
# subplots 可以直接返回 fig 和 ax
fig, (ax1, ax2) = plt.subplots(1, 2)
ax1.plot(x, y, 'r*-', label='sin(x)')
ax2.plot(x, z, 'b^--', label='cos(x)')
fig.legend()
fig.show()
# 保存图片需要调用函数
fig.savefig('test.png')
本文章使用limfx的vsocde插件快速发布