1.条形图
bar(水平坐标, 绝对高度, 相对宽度, color=颜色,
label=图例标签, alpha=透明度)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
# 生成数据
apples = np.array([30, 25, 22, 36, 21, 29,
20, 24, 33, 19, 27, 15])
oranges = np.array([24, 33, 19, 27, 35, 20,
15, 27, 20, 32, 20, 22])
# 创建图形窗口
mp.figure('Bar', facecolor='lightgray')
# 设置窗口标题
mp.title('Bar', fontsize=20)
# 设置坐标轴标签
mp.xlabel('Month', fontsize=14)
mp.ylabel('Price', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 设置网格线型
mp.grid(axis='y', linestyle=':')
# 设置垂直坐标范围
mp.ylim(0, 40)
# 绘制条形图
x = np.arange(len(apples))
mp.bar(x, apples, 0.4, color='dodgerblue',
label='Apple')
mp.bar(x + 0.3, oranges, 0.4, color='orangered',
label='Orange', alpha=0.75)
# 设置水平坐标刻度标签
mp.xticks(x + 0.1, (
'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
# 绘制图例
mp.legend()
# 显示图形
mp.show()
效果图:
2.饼图
pie(值数组, 间隙数组, 标签数组, 颜色数组, 格式,
shadow=是否带阴影, startangle=起始角度)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import matplotlib.pyplot as mp
# 生成数据
values = [26, 17, 21, 29, 11]
spaces = [0.05, 0.01, 0.01, 0.01, 0.01]
labels = ['Python', 'JavaScript', 'C++', 'Java', 'PHP']
colors = ['dodgerblue', 'orangered', 'limegreen', 'violet', 'gold']
# 创建图形窗口
mp.figure('Pie', facecolor='lightgray')
# 设置窗口标题
mp.title('Pie', fontsize=20)
# 绘制饼图
mp.pie(values, spaces, labels, colors, '%d%%',
shadow=True, startangle=90)
# 设置纵横比为1:1
mp.axis('equal')
# 显示图形
mp.show()
效果图:
3.等高线图
contour(点阵X坐标矩阵, 点阵Y坐标矩阵, 点阵Z坐标矩阵,
梯度数, colors=颜色, linewidths=线宽)
contourf(点阵X坐标矩阵, 点阵Y坐标矩阵, 点阵Z坐标矩阵,
梯度数, cmap=颜色映射)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
# 生成数据
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(
-x ** 2 - y ** 2)
# 创建图形窗口
mp.figure('Contour', facecolor='lightgray')
# 设置窗口标题
mp.title('Contour', fontsize=20)
# 设置坐标轴标签
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 设置网格线型
mp.grid(linestyle=':')
# 绘制等高线图
mp.contourf(x, y, z, 8, cmap='jet')
cntr = mp.contour(x, y, z, 8, colors='black',
linewidths=0.5)
# 在等高线上标注高度
mp.clabel(cntr, inline_spacing=1, fmt='%.1f',
fontsize=10)
# 显示图形
mp.show()
效果图:
4.热力图
10 13 12 56
22 26 27 19 -cmap->颜色
55 42 25 36
imshow(矩阵, cmap=颜色映射, origin=纵轴方向)
图片
* * * *
* * * *
* * * *
* * * *
(129,200,300)(B,G,R)(B,G,R)(B,G,R)
( B , G , R )(B,G,R)(B,G,R)(B,G,R)
( B , G , R )(B,G,R)(B,G,R)(B,G,R)
( B , G , R )(B,G,R)(B,G,R)(B,G,R)
| 灰度化
v
Y Y Y Y
Y Y Y Y -gray->灰度图像
Y Y Y Y
Y Y Y Y
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
# 生成数据
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(
-x ** 2 - y ** 2)
# 创建图形窗口
mp.figure('Hot', facecolor='lightgray')
# 设置窗口标题
mp.title('Hot', fontsize=20)
# 设置坐标轴标签
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 设置网格线型
mp.grid(linestyle=':')
# 绘制热力图
mp.imshow(z, cmap='jet', origin='low')
# 显示图形
mp.show()
效果图:
灰度化
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import scipy.misc as sm
import matplotlib.pyplot as mp
image = sm.imread(
'../../data/lily.jpg', True).astype(np.uint8)
mp.figure('Image', facecolor='lightgray')
mp.title('Lily', fontsize=20)
mp.axis('off') # 关闭坐标轴
mp.imshow(image, cmap='gray')
mp.show()
效果图:
5.网格线
ax = gca()
ax.grid(which='major/minor', axis='x/y/both',
linewidth=线宽, linestyle=线型, color=颜色)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
x = np.linspace(-10, 10, 1000)
y = 8 * np.sinc(x) # 减幅正弦函数
# 创建图形窗口
mp.figure('Grid', facecolor='lightgray')
# 设置标题
mp.title('Grid', fontsize=20)
# 设置坐标标签
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 设置网格线
ax = mp.gca()
ax.xaxis.set_minor_locator(
mp.MultipleLocator(0.5))
ax.yaxis.set_minor_locator(
mp.MultipleLocator(0.4))
ax.grid(which='major', axis='both',
linewidth=0.75, linestyle='-',
color='orange')
ax.grid(which='minor', axis='both',
linewidth=0.25, linestyle='-',
color='orange')
mp.plot(x, y, c='dodgerblue',
label=r'$y=8sinc(x)$')
mp.legend()
mp.show()
效果图:
6.半对数坐标
semilogy(同plot)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
y = np.array([1, 10, 100, 1000, 100, 10, 1])
mp.figure('Grid', facecolor='lightgray')
mp.subplot(211)
mp.title('Normal', fontsize=20)
mp.ylabel('y', fontsize=14)
ax = mp.gca()
ax.xaxis.set_major_locator(
mp.MultipleLocator(1))
ax.xaxis.set_minor_locator(
mp.MultipleLocator(0.1))
ax.yaxis.set_major_locator(
mp.MultipleLocator(250))
ax.yaxis.set_minor_locator(
mp.MultipleLocator(50))
ax.grid(which='major', axis='both',
linewidth=0.75, linestyle='-',
color='orange')
ax.grid(which='minor', axis='both',
linewidth=0.25, linestyle='-',
color='orange')
mp.tick_params(labelsize=10)
mp.plot(y, c='dodgerblue', label='plot')
mp.legend()
mp.subplot(212)
mp.title('Log', fontsize=20)
mp.xlabel('x', fontsize=14)
mp.ylabel('y', fontsize=14)
ax = mp.gca()
ax.xaxis.set_major_locator(
mp.MultipleLocator(1))
ax.xaxis.set_minor_locator(
mp.MultipleLocator(0.1))
ax.grid(which='major', axis='both',
linewidth=0.75, linestyle='-',
color='orange')
ax.grid(which='minor', axis='both',
linewidth=0.25, linestyle='-',
color='orange')
mp.tick_params(labelsize=10)
mp.semilogy(y, c='dodgerblue', label='semilogy')
mp.legend()
mp.tight_layout()
mp.show()
效果图:
7.极坐标系
gca(projection='polar') # 创建极坐标图
plot/scatter(极角, 极径, ...)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
t = np.linspace(0, 2 * np.pi, 1000)
r_spiral = 0.8 * t
r_rose = 5 * np.sin(6 * t)
mp.figure('Polar', facecolor='lightgray')
mp.gca(projection='polar') # 创建极坐标系
mp.title('Polar', fontsize=20)
mp.xlabel(r'$\theta$', fontsize=14)
mp.ylabel(r'$\rho$', fontsize=14)
mp.grid(linestyle=':')
mp.plot(t, r_spiral, c='dodgerblue',
label=r'$\rho=0.8\theta$')
mp.plot(t, r_rose, c='orangered',
label=r'$\rho=5sin(6\theta)$')
mp.legend()
mp.show()
效果图:
8.三维坐标系
from mpl_toolkits.mplot3d import axes3d
ax = gca(projection='3d') # 创建三维坐标系
1)三维散点
ax.scatter(X坐标, Y坐标, Z坐标, s=大小, marker=点形,
edgecolor=边缘色, facecolor=填充色,
zorder=Z顺序)
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
n = 1000
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
z = np.random.normal(0, 1, n)
d = np.sqrt(x ** 2 + y ** 2 + z ** 2)
mp.figure('3D Scatter')
ax = mp.gca(projection='3d') # 创建三维坐标系
mp.title('3D Scatter', fontsize=20)
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
mp.tick_params(labelsize=10)
ax.scatter(x, y, z, s=60, c=d, cmap='jet_r',
alpha=0.5)
mp.show()
效果图:
2)空间曲面
ax.plot_surface(
点阵X坐标矩阵, 点阵Y坐标矩阵, 点阵Z坐标矩阵,
rstride=行跨距, cstride=列跨距, cmap=颜色映射) # 表面
ax.plot_wireframe(
点阵X坐标矩阵, 点阵Y坐标矩阵, 点阵Z坐标矩阵,
rstride=行跨距, cstride=列跨距, linewidth=线宽,
color=颜色) # 线框
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
from mpl_toolkits.mplot3d import axes3d
# 生成数据
n = 1000
x, y = np.meshgrid(np.linspace(-3, 3, n),
np.linspace(-3, 3, n))
z = (1 - x / 2 + x ** 5 + y ** 3) * np.exp(
-x ** 2 - y ** 2)
# 创建图形窗口
mp.figure('3D Wireframe')
# 创建三维坐标系
ax = mp.gca(projection='3d')
# 设置窗口标题
mp.title('3D Wireframe', fontsize=20)
# 设置坐标轴标签
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 绘制三维线框图
ax.plot_wireframe(
x, y, z, rstride=30, cstride=30,
linewidth=0.5, color='dodgerblue')
# 创建图形窗口
mp.figure('3D Surface')
# 创建三维坐标系
ax = mp.gca(projection='3d')
# 设置窗口标题
mp.title('3D Surface', fontsize=20)
# 设置坐标轴标签
ax.set_xlabel('x', fontsize=14)
ax.set_ylabel('y', fontsize=14)
ax.set_zlabel('z', fontsize=14)
# 设置刻度参数
mp.tick_params(labelsize=10)
# 绘制三维表面图
ax.plot_surface(
x, y, z, rstride=10, cstride=10, cmap='jet')
# 显示图形
mp.show()
效果图一:
效果图二:
9.动画
通过连续显示的静态画面生成动画效果。
import matplotlib.animation as ma
def 更新函数 (序号) {
...
}
ma.FuncAnimation(图形窗口, 更新函数,
interval=间隔时间(毫秒))
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
n_bubbles = 100
bubbles = np.zeros(n_bubbles, dtype=[
('position', float, 2),
('size', float),
('growth', float),
('color', float, 4)])
bubbles['position'] = np.random.uniform(
0, 1, (n_bubbles, 2))
bubbles['size'] = np.random.uniform(
50, 750, n_bubbles)
bubbles['growth'] = np.random.uniform(
30, 150, n_bubbles)
bubbles['color'] = np.random.uniform(
0, 1, (n_bubbles, 4))
mp.figure('Bubbles', facecolor='lightgray')
mp.title('Bubbles', fontsize=20)
mp.xticks(())
mp.yticks(())
sc = mp.scatter(bubbles['position'][:, 0],
bubbles['position'][:, 1],
s=bubbles['size'],
c=bubbles['color'])
def update(number):
bubbles['size'] += bubbles['growth']
burst = number % n_bubbles
bubbles['position'][burst] = \
np.random.uniform(0, 1, 2)
bubbles['size'][burst] = 0
bubbles['growth'][burst] = \
np.random.uniform(30, 150)
bubbles['color'][burst] = \
np.random.uniform(0, 1, 4)
sc.set_offsets(bubbles['position'])
sc.set_sizes(bubbles['size'])
sc.set_facecolor(bubbles['color'])
anim = ma.FuncAnimation(mp.gcf(), update,
interval=10)
mp.show()
效果图:
使用生成器
def 更新函数 (数据) {
...
}
def 生成器函数 () {
...
yield 数据
}
ma.FuncAnimation(图形窗口, 更新函数,生成器函数,
interval=间隔时间(毫秒))
代码:
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
import numpy as np
import matplotlib.pyplot as mp
import matplotlib.animation as ma
mp.figure('Signal', facecolor='lightgray')
mp.title('Signal', fontsize=20)
mp.xlabel('Time', fontsize=14)
mp.ylabel('Signal', fontsize=14)
ax = mp.gca()
ax.set_ylim(-3, 3)
ax.set_xlim(0, 10)
mp.tick_params(labelsize=10)
mp.grid(linestyle=':')
pl = mp.plot([], [], c='orangered')[0] # 创建曲线
pl.set_data([], []) # 创建曲线数据缓冲区(空)
def update(data):
t, v = data
x, y = pl.get_data() # 获取曲线数据缓冲区
x.append(t)
y.append(v)
x_min, x_max = ax.get_xlim()
if t >= x_max:
ax.set_xlim(t - (x_max - x_min), t)
ax.figure.canvas.draw() # 重绘坐标系
pl.set_data(x, y) # 更新曲线数据缓冲区
def generator():
t = 0
while True:
v = np.sin(2 * np.pi * t) * np.exp(
np.sin(0.3 * np.pi * t))
yield t, v
t += 0.05
anim = ma.FuncAnimation(mp.gcf(), update,
generator, interval=5)
mp.show()