Matplotlib是Python中最常用的可视化工具之一,可以非常方便地创建海量类型地2D图表和一些基本的3D图表。因为在函数的设计上参考了MATLAB,所以叫做Matplotlib。
一.matplotlib API入门
matplotlib的通常引入约定:
import matplotlib.pyplot as plt
1.Figure
matplotlib的图像都位于Figure对象中。你可以用plt.figure创建一个新的Figure:
plt.figure有一些选项,特别是figsize,它用于确保当图片保存到磁盘时具有一定的大小和纵横比。
fig = plt.figure()
2. subplot子图
add_subplot:向figure对象中添加子图。
add_subplot(a, b, c):a,b 表示讲fig分割成axb的区域,c 表示当前选中要操作的区域(c从1开始)。
add_subplot返回的是AxesSubplot对象,plot 绘图的区域是最后一次指定subplot的位置
import matplotlib.pyplot as plt
fig = plt.figure()
ax1 = fig.add_subplot(2, 2, 1)
ax2 = fig.add_subplot(2, 2, 2)
ax3 = fig.add_subplot(2, 2, 3)
plt.show()
3.线图
random_arr = randn.rand(50)
# 默认是在最后一次使用subplot的位置上作图
plt.plot(random_arr,'ro--') # r:表示颜色为红色,o:表示数据用o标记 ,--:表示虚线
# 等价于:
# plt.plot(random_arr,linestyle='--',color='r',marker='o')
plt.show()
4.直方图
# hist:直方图:统计分布情况
plt.hist(np.random.rand(8), bins=6, color='b', alpha=0.3) # bins:数据箱子个数
'''
(array([ 3., 0., 0., 0., 2., 3.]),
array([ 0.10261627, 0.19557319, 0.28853011, 0.38148703, 0.47444396,
0.56740088, 0.6603578 ]),
<a list of 6 Patch objects>)
'''
5.散点图
plt.scatter(np.arange(30), np.arange(30) + 3 * randn.randn(30))
6.subplots :生成子图/子图数组
# 柱状图
fig, ax = plt.subplots()
x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
ax.bar(x, y1, width, color='r') # 画柱子
ax.bar(x+width, y2, width, color='g') # 画柱子
ax.set_xticks(x+width)
ax.set_xticklabels(['a', 'b', 'c', 'd', 'e']) # 下标注明
fig, axes = plt.subplots(2, 2, sharex=True, sharey=True) # 共享轴坐标
random_arr = randn.randn(8)
fig, axes = plt.subplots(2, 2)
axes[0, 0].hist(random_arr, bins=16, color='k', alpha=0.5)
axes[0, 1].plot(random_arr,'ko--')
x = np.arange(8)
y = x + 5 * np.random.rand(8)
axes[1,0].scatter(x, y)
x = np.arange(5)
y1, y2 = np.random.randint(1, 25, size=(2, 5))
width = 0.25
axes[1,1].bar(x, y1, width, color='r') # 画柱子
axes[1,1].bar(x+width, y2, width, color='g') # 画柱子
axes[1,1].set_xticks(x+width)
axes[1,1].set_xticklabels(['a', 'b', 'c', 'd', 'e']) # 下标注明
7.重叠绘制和显示图例
random_arr1 = randn.randn(8)
random_arr2 = randn.randn(8)
fig, ax = plt.subplots()
ax.plot(random_arr1,'ko--',label='A')
ax.plot(random_arr2,'b^--',label='B')
plt.legend(loc='best') # 自动选择放置图例的最佳位置
- 设置刻度范围:set_xlim、set_ylim
- 设置显示的刻度:set_xticks、set_yticks
- 刻度标签:set_xticklabels、set_yticklabels
- 坐标轴标签:set_xlabel、set_ylabel
- 图像标题:set_title
fig, ax = plt.subplots(1)
ax.plot(np.random.randn(380).cumsum())
# 设置刻度范围
ax.set_xlim([0, 500])
# 设置显示的刻度(记号)
ax.set_xticks(range(0,500,100))
# 设置刻度标签
ax.set_xticklabels(['one', 'two', 'three', 'four', 'five'],
rotation=30, fontsize='small')
# 设置坐标轴标签
ax.set_xlabel('X:...')
ax.set_ylabel('Y:...')
# 设置标题
ax.set_title('Example')
8.Plotting functions in pandas
import matplotlib.pyplot as plt
import numpy as np
from pandas import Series
fig = plt.figure()
s = Series(np.random.randn(10).cumsum(), index=np.arange(0, 100, 10))
fig,ax = plt.subplots(1)
s.plot(ax=ax,style='ko--')
plt.show()
9.2D图表
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
# 通过rcParams设置全局横纵轴字体大小
mpl.rcParams['xtick.labelsize'] = 24
mpl.rcParams['ytick.labelsize'] = 24
np.random.seed(42)
# x轴的采样点
x = np.linspace(0, 5, 100)
# 通过下面曲线加上噪声生成数据,所以拟合模型就用y了……
y = 2*np.sin(x) + 0.3*x**2
y_data = y + np.random.normal(scale=0.3, size=100)
# figure()指定图表名称
plt.figure('data')
# '.'标明画散点图,每个散点的形状是个圆
plt.plot(x, y_data, '.')
# 画模型的图,plot函数默认画连线图
plt.figure('model')
plt.plot(x, y)
# 两个图画一起
plt.figure('data & model')
# 通过'k'指定线的颜色,lw指定线的宽度
# 第三个参数除了颜色也可以指定线形,比如'r--'表示红色虚线
# 更多属性可以参考官网:http://matplotlib.org/api/pyplot_api.html
plt.plot(x, y, 'k', lw=3)
# scatter可以更容易地生成散点图
plt.scatter(x, y_data)
# 将当前figure的图保存到文件result.png
plt.savefig('result.png')
# 一定要加上这句才能让画好的图显示在屏幕上
plt.show()
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.rcParams['axes.titlesize'] = 20
mpl.rcParams['xtick.labelsize'] = 16
mpl.rcParams['ytick.labelsize'] = 16
mpl.rcParams['axes.labelsize'] = 16
mpl.rcParams['xtick.major.size'] = 0
mpl.rcParams['ytick.major.size'] = 0
# 包含了狗,猫和猎豹的最高奔跑速度,还有对应的可视化颜色
speed_map = {
'dog': (48, '#7199cf'),
'cat': (45, '#4fc4aa'),
'cheetah': (120, '#e1a7a2')
}
# 整体图的标题
fig = plt.figure('Bar chart & Pie chart')
# 在整张图上加入一个子图,121的意思是在一个1行2列的子图中的第一张
ax = fig.add_subplot(121)
ax.set_title('Running speed - bar chart')
# 生成x轴每个元素的位置
xticks = np.arange(3)
# 定义柱状图每个柱的宽度
bar_width = 0.5
# 动物名称
animals = speed_map.keys()
# 奔跑速度
speeds = [x[0] for x in speed_map.values()]
# 对应颜色
colors = [x[1] for x in speed_map.values()]
# 画柱状图,横轴是动物标签的位置,纵轴是速度,定义柱的宽度,同时设置柱的边缘为透明
bars = ax.bar(xticks, speeds, width=bar_width, edgecolor='none')
# 设置y轴的标题
ax.set_ylabel('Speed(km/h)')
# x轴每个标签的具体位置,设置为每个柱的中央
ax.set_xticks(xticks+bar_width/2)
# 设置每个标签的名字
ax.set_xticklabels(animals)
# 设置x轴的范围
ax.set_xlim([bar_width/2-0.5, 3-bar_width/2])
# 设置y轴的范围
ax.set_ylim([0, 125])
# 给每个bar分配指定的颜色
for bar, color in zip(bars, colors):
bar.set_color(color)
# 在122位置加入新的图
ax = fig.add_subplot(122)
ax.set_title('Running speed - pie chart')
# 生成同时包含名称和速度的标签
labels = ['{}\n{} km/h'.format(animal, speed) for animal, speed in zip(animals, speeds)]
# 画饼状图,并指定标签和对应颜色
ax.pie(speeds, labels=labels, colors=colors)
plt.show()
10.3D图表
import matplotlib.pyplot as plt
import numpy as np
# 3D图标必须的模块,project='3d'的定义
from mpl_toolkits.mplot3d import Axes3D
np.random.seed(42)
n_grids = 51 # x-y平面的格点数
c = n_grids / 2 # 中心位置
nf = 2 # 低频成分的个数
# 生成格点
x = np.linspace(0, 1, n_grids)
y = np.linspace(0, 1, n_grids)
# x和y是长度为n_grids的array
# meshgrid会把x和y组合成n_grids*n_grids的array,X和Y对应位置就是所有格点的坐标
X, Y = np.meshgrid(x, y)
# 生成一个0值的傅里叶谱
spectrum = np.zeros((n_grids, n_grids), dtype=np.complex)
# 生成一段噪音,长度是(2*nf+1)**2/2
noise = [np.complex(x, y) for x, y in np.random.uniform(-1,1,((2*nf+1)**2/2, 2))]
# 傅里叶频谱的每一项和其共轭关于中心对称
noisy_block = np.concatenate((noise, [0j], np.conjugate(noise[::-1])))
# 将生成的频谱作为低频成分
spectrum[c-nf:c+nf+1, c-nf:c+nf+1] = noisy_block.reshape((2*nf+1, 2*nf+1))
# 进行反傅里叶变换
Z = np.real(np.fft.ifft2(np.fft.ifftshift(spectrum)))
# 创建图表
fig = plt.figure('3D surface & wire')
# 第一个子图,surface图
ax = fig.add_subplot(1, 2, 1, projection='3d')
# alpha定义透明度,cmap是color map
# rstride和cstride是两个方向上的采样,越小越精细,lw是线宽
ax.plot_surface(X, Y, Z, alpha=0.7, cmap='jet', rstride=1, cstride=1, lw=0)
# 第二个子图,网线图
ax = fig.add_subplot(1, 2, 2, projection='3d')
ax.plot_wireframe(X, Y, Z, rstride=3, cstride=3, lw=0.5)
plt.show()