Matplotlib – 高级绘图
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams['font.family'] = ['Arial Unicode MS', 'Microsoft Yahei', 'SimHei', 'sans-serif']
%matplotlib notebook
三维图像
三维图像主要用于三维数据可视化
from mpl_toolkits.mplot3d import Axes3D # 载入三维子库
# 0-100之间,随机数,生成20个,做坐标轴坐标
np.random.randint(0, 100, 20)
array([24, 49, 47, 35, 21, 54, 23, 95, 49, 7, 39, 95, 58, 80, 37, 35, 92,
26, 73, 54])
fig = plt.figure() # 生成父对象
ax = Axes3D(fig) # 生成三维子图
x = np.random.randint(0, 100, 20)
y = np.random.randint(0, 100, 20)
z = np.random.randint(0, 100, 20)
ax.scatter(x, y, z, s=z*3, c=z, alpha=0.5)
ax.plot(x, y, z, alpha=0.5)
<IPython.core.display.Javascript object>
image.png
[<mpl_toolkits.mplot3d.art3d.Line3D at 0x6c92da0>]
动画
import random
from matplotlib.animation import FuncAnimation # 载入动画子库
fig, ax = plt.subplots()
def update(i): # i是帧编号1,2,3...最后一帧
plt.title(i)
plt.plot([1,2])
# 动画方法
ani = FuncAnimation(
fig, # 动画应用的图像
update, # 动画每帧都要调用的函数
interval = 100, # 动画帧间隔,毫秒,大了动画慢,小了动画快
frames = 50, # 动画帧数,对GIF有效,值调用函数内的i可以获取。可自定义值如range(50,100)
)
<IPython.core.display.Javascript object>
image.png
案例:股票走势模拟
random.randint(-10, 10),
(-2,)
fig, ax = plt.subplots()
line = []
def update(i):
plt.title(i)
# 原理:固定的图像
# plt.plot([1,2,3])
# plt.scatter([5], [10])
# 散点图动画
# x = random.randint(-10, 10)
# y = random.randint(-10, 10)
# plt.scatter(x, y)
# 折线图,股票价格走势
y2 = random.randint(-1, 1)
# plt.plot([2, 3]) # 最少两个节点才能画出一条线
line.append(y2) # 追加
plt.plot(np.array(line).cumsum(), color='red') # 生成数组,累加历史价格
# 动画方法
ani = FuncAnimation(
fig, # 动画应用的图像
update, # 动画每帧都要调用的函数
interval = 100, # 动画帧间隔,毫秒,大了动画慢,小了动画快
frames = 50, # 动画帧数,对GIF有效,值调用函数内的i可以获取。可自定义值如range(50,100)
)
plt.grid(linewidth=0.2, alpha=0.5)
# 动画保存,某些系统和环境下不能使用,根据情况选用
# ani.save('line.html', dpi=72) # 保存为HTML
# 动画如需保存为GIF图片,系统内必须安装imagemagick,(Ubuntu默认可用),测试Windows有的不可用
ani.save('line.gif', dpi=72, writer='imagemagick') # 保存为GIF
<IPython.core.display.Javascript object>
image.png
line
np.array(line)
np.array(line).cumsum() # 累加
array([ 1, 2, 1, 1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 3, 2, 3, 4,
4, 5, 5, 5, 5, 4, 3, 4, 3, 4, 4, 3, 4, 3, 2, 3, 3,
4, 3, 2, 3, 2, 2, 2, 3, 2, 2, 3, 2, 1, 1, 2, 3, 2,
3, 4, 5, 6, 5, 4, 5, 6, 7, 6, 5, 5, 5, 6, 6, 7, 6,
5, 5, 4, 3, 4, 4, 5, 4, 3, 4, 5, 5, 5, 5, 5, 4, 3,
3, 4, 5, 6, 7, 7, 8, 9, 9, 10, 11, 11, 12, 12, 12, 13, 13,
13, 12, 12, 13, 12, 13, 12, 12, 11, 11, 11, 12, 13, 13, 12, 12, 13,
12, 13, 14, 14, 14, 15, 14, 13, 12, 12, 11, 11, 11, 12, 11, 11, 11],
dtype=int32)
数学或科研展示图像
绘制一个简单线性函数,和非线性函数图像
np.arange(-50, 50, 10) # 起始值结束值自增,步长10
array([-50, -40, -30, -20, -10, 0, 10, 20, 30, 40])
np.linspace(-10, 10, 20) # 将起始值和结束值等分为20份
array([-10. , -8.94736842, -7.89473684, -6.84210526,
-5.78947368, -4.73684211, -3.68421053, -2.63157895,
-1.57894737, -0.52631579, 0.52631579, 1.57894737,
2.63157895, 3.68421053, 4.73684211, 5.78947368,
6.84210526, 7.89473684, 8.94736842, 10. ])
%matplotlib inline
plt.figure(figsize=(7, 5), dpi=150)
# 线性函数:y=kx+b
x = np.array([-50,-15,0,5,8,15,50])
k = 2
b = 10
y = k * x + b
y
plt.plot(x, (k * x), label='2*x+10')
plt.plot(x, (10 * x + 100), label='5*x')
# 非线性函数
# x2 = np.array([-50,-15,0,5,8,15,50]) # 数据太少,曲线不平滑
x2 = np.linspace(-25, 25, 100) # 100个坐标值
y2 = x2 ** 2
y2
plt.plot(x2, y2, label='x**2')
###########################################33
# 坐标轴标注
plt.xticks(np.arange(-50, 50, 5))
plt.yticks(np.arange(-200, 400, 50))
plt.legend() # 图例
plt.grid(linewidth=0.2, alpha=0.5) # 网格
# 操作轴线
# gca,get corrent axis,获取轴
ax = plt.gca()
# 去除上侧和右侧的空白轴线
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 移位轴线
ax.spines['bottom'].set_position(['data', 0])
ax.spines['left'].set_position(['data', 0])
output_18_0.png
plt.figure(figsize=(10, 6), dpi=200)
# 线性函数:y=kx+b
x = np.array([-50,-15,0,5,8,15,50])
k = 2
b = 30
y = k * x + b
plt.plot(x, y)
# 组件
# 标题,可以使用$引入部分latex文本排版语法和公式
plt.title('线性 $y=ax+b$,非线性 $y=ax^{2}+bx+c$')
# 坐标轴标注,当字符串里有反斜杠等转义特殊字符时,字符串前加`r`,表示显示原始字符串
plt.xlabel(r'x \axis')
###############
# 操作轴线
# gca,get corrent axis,获取轴
ax = plt.gca()
# 交换轴线
# ax.xaxis.set_ticks_position('top')
# ax.yaxis.set_ticks_position('right')
# # 去除上侧和右侧的空白轴线
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# # 移位轴线
ax.spines['bottom'].set_position(['data', -10]) # y轴在x轴-10处
ax.spines['left'].set_position(['data', 0])
###############
# 添加注解标识
# 标记点
x0 = -10
y0 = k * x0 + b
plt.scatter(x0, y0, color='red')
# 标记线
plt.plot(
[x0, x0],
[y0, -10],
linestyle='--',
color='green',
)
plt.plot(
[x0, 0],
[y0, y0],
linestyle='-.',
color='yellow',
)
#################################
# 任意位置增加文本
plt.text(
20,
75,
'我是图片内文本!',
fontsize=18,
rotation=30,
)
# 任意位置增加带箭头的注释文本
plt.annotate(
r'$Linear\ function\ y=ax+b$', #显示字符串,空格在$内不显示,用反斜杠转义
xytext=(-45, 100), # 文本位置
xy=(x0, y0), # 箭头指向位置
arrowprops=dict( # 字典类型,定义箭头样式
arrowstyle = 'fancy', # 箭头样式,例如 ->,<-,|-|,simple,fancy
color = 'green', # 箭头颜色
connectionstyle="arc3,rad=.5", # 箭头弧度
),
# 下面两个参数将绝对坐标位置设为相对坐标
# xycoords = 'data', # 相对默认坐标系偏移
# textcoords = 'offset points', # 相对坐标,相对箭头原点偏移
)
Text(-45,100,'$Linear\\ function\\ y=ax+b$')
output_19_1.png