- 导入必要的包
import matplotlib.pyplot as plt
from numpy import *
import numpy as np
%matplotlib inline
- 画图
x = linspace(0, 2 * pi, 50)
plt.plot(sin(x));
plt.plot(x, sin(x));
- 使用字符串,给定线条参数:
plt.plot(x, sin(x), 'b-o',
x, sin(2 * x), 'r-^');
- 二维散点图
plt.plot(x, sin(x), 'bo');
plt.scatter(x, sin(x));
x = random.rand(200)
y = random.rand(200)
size = random.rand(200) * 30
color = random.rand(200)
plt.scatter(x, y, size, color)
# 显示颜色条
plt.colorbar();
- 多图–使用figure()命令产生新的图像:
import matplotlib
matplotlib.rcParams['axes.unicode_minus'] = False
t = linspace(0, 2*pi, 50)
x = sin(t)
y = cos(t)
plt.figure()
plt.plot(x)
plt.figure()
plt.plot(y);
使用 subplot 在一幅图中画多幅子图:subplot(row, column, index)
plt.subplot(1, 2, 1)
plt.plot(x)
plt.subplot(1, 2, 2)
plt.plot(y);
默认多次 plot 会叠加,可以在 plot 中加入 label ,使用 legend 加上图例:
plt.plot(x, label='sin')
plt.plot(y, label='cos')
plt.legend();
#或
plt.plot(x)
plt.plot(y)
plt.legend(['sin', 'cos']);
可以设置坐标轴的标签和标题:
x = linspace(0, 2 * pi, 50)
plt.plot(x, sin(x))
plt.xlabel('radians')
# 可以设置字体大小
plt.ylabel('amplitude', fontsize='large')
plt.title('Sin(x)');
用 ‘grid()’ 来显示网格:
plt.plot(x, sin(x))
plt.xlabel('radians')
plt.ylabel('amplitude', fontsize='large')
plt.title('Sin(x)')
plt.grid();
从高斯分布随机生成1000个点得到的直方图:
plt.hist(np.random.randn(1000));
饼图:
import matplotlib.pyplot as plt
labels = u'苹果', u'香蕉', u'葡萄'
sizes = [100, 200, 250]
plt.pie(sizes, labels=labels, autopct='%3.2f%%',)
plt.axis('equal') # Equal aspect ratio ensures that pie is drawn as a circle.
plt.show()