Matplotlib总结
文章目录
1、简单图形绘制
import numpy as np
import matplotlib.pyplot as plt
def func1():
x = np.arange(1, 10, 0.1)
y = np.sin(x)
plt.plot(x, y, 'g', lw=1) # 折线图,颜色是green
x = np.arange(1, 10, 1)
y = np.sin(x)
plt.bar(x, y, 0.2, alpha=1, color='b') # 柱状图,颜色是blue
plt.show()
if __name__ == '__main__':
func1()
2、figure的简单使用
figure 即打开一个图例窗口,常用参数如下:
param | desc |
---|---|
num | 图例序号 |
figsize | 图例大小 |
def func2():
x = np.linspace(-1, 10, 50)
# figure 1
y1 = np.sin(x)
plt.figure(num=1)
plt.plot(x, y1)
# figure 0
y2 = np.log10(x)
plt.figure(num=0)
plt.plot(x, y2)
# figure 3 指定线的颜色, 宽度和类型
plt.figure(num=3, figsize=(4, 4))
plt.plot(x, y1)
plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--')
plt.show()
3、坐标轴相关
3.1、设置坐标轴刻度
def func31():
x = np.linspace(0, 10, 50)
y = np.sin(x)
plt.plot(x, y, color='red', linewidth=1.0, linestyle='--')
# 设置坐标轴的取值范围
plt.xlim((0, 10))
plt.ylim((-1, 1))
# 设置坐标轴的lable
# 标签里面必须添加字体变量:fontproperties='SimHei',fontsize=20。不然可能会乱码
plt.xlabel(u'x轴', fontproperties='SimHei', fontsize=20)
plt.ylabel(u'y轴', fontproperties='SimHei', fontsize=20)
plt.xticks(np.linspace(0, 10, 5))
plt.show()
3.2、设置坐标轴位置
一个图例有4个边框,分别为right,left,top,bottom
def func32():
# 绘制普通图像
x = np.linspace(0, 10, 50)
y = np.sin(x)
plt.plot(x, y, color='red', linewidth=1.0, linestyle='--')
# 设置坐标轴的取值范围
plt.xlim((0, 10))
plt.ylim((-1, 1))
# 设置坐标轴的lable
# 标签里面必须添加字体变量:fontproperties='SimHei',fontsize=20。不然可能会乱码
plt.xlabel(u'x轴', fontproperties='SimHei', fontsize=20)
plt.ylabel(u'y轴', fontproperties='SimHei', fontsize=20)
plt.xticks(np.linspace(0, 10, 5))
# 获取当前的坐标轴, gca = get current axis
ax = plt.gca()
# 隐藏左边框和上边框
ax.spines['top'].set_color('none')
ax.spines['left'].set_color('none')
# # 设置x坐标轴为下边框
ax.xaxis.set_ticks_position('bottom')
# # 设置y坐标轴为右边框
ax.yaxis.set_ticks_position('right')
# 设置x轴, y轴在(5, -1)的位置
ax.spines['right'].set_position(('data', 5))
ax.spines['bottom'].set_position(('data', -1))
plt.show()
4、绘制点和注解
def func4():
x = np.linspace(0, 10, 50)
y = np.sin(x)
plt.plot(x, y, color='b', linewidth=2, linestyle='--')
# 定义(x0, y0)点
x0 = np.pi / 2
y0 = np.sin(x0)
# 绘制(x0, y0)点
plt.scatter(x0, y0, s=100, color='red') # s 设置点大小
# 绘制注解一
plt.annotate(r'$sin(x) = %s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle='arc3, rad=.2'))
# 绘制注解二
plt.text(0, 0, r'$cos^2(x) + sin^2(x) = 1$', fontdict={'size': 16, 'color': 'red'})
plt.show()
5、绘制散点图
def func5():
# 数据个数
n = 1024
# 均值为0, 方差为1的随机数
x = np.random.normal(0, 1, n)
y = np.random.normal(0, 1, n)
# 计算颜色值
color = np.arctan2(y, x)
# 绘制散点图
plt.scatter(x, y, s=75, c=color, alpha=0.5)
# 绘制散点图
plt.scatter(x, y, c=color, s=75, alpha=0.5)
plt.show()
6、绘制等高线图
from matplotlib.colors import ListedColormap
def func6():
cmap = ListedColormap(
['#FFAAAA', '#AAFFAA', '#AAAAFF', '#FF0000', '#00FF00', '#0000FF'])
# 定义等高线高度函数
def f(x, y):
return (1 - x / 2 + x ** 5 + y ** 3) * np.exp(- x ** 2 - y ** 2)
# 数据数目
n = 256
# 定义x, y
x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
# 生成网格数据
X, Y = np.meshgrid(x, y) # X,Y 的shape为(256,256),经过函数f后值也是(256,256)
# 填充等高线的颜色, 8是等高线分为几部分
plt.contourf(X, Y, f(X, Y), 8, alpha=0.75, cmap=cmap)
# 绘制等高线
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=0.5)
# 绘制等高线数据
plt.clabel(C, inline=True, fontsize=10)
plt.show()
7、绘制Image
def func7():
# 定义图像数据
a = np.linspace(0, 1, 9).reshape(3, 3)
# 显示图像数据
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
# 添加颜色条
plt.colorbar()
plt.show()
8、绘制多图
8.1、subplot多图
def func81():
plt.figure()
x = [0, 1, 2]
y = [0, 1, 2]
# 绘制第一个图
plt.subplot(2, 1, 1) # 2 * 1 图,选第一个
plt.plot(x, y)
# 绘制第二个图
plt.subplot(2, 2, 3) # 2 * 1 图,选第三个
plt.plot(x, y)
# 绘制第三个图
plt.subplot(2, 2, 4) # 2 * 1 图,选第四个
plt.plot(x, y)
plt.show()
8.2、figure多图
def func82():
x = [0, 1, 2]
y = [0, 1, 2]
# 定义figure
plt.figure()
# figure分成2行2列, 取得第一个子图的句柄, 第一个子图跨度为1行2列, 起点是表格(0, 0)
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2, rowspan=1)
ax1.plot(x, y)
ax2 = plt.subplot2grid((2, 2), (1, 0), colspan=1, rowspan=1)
ax2.plot(x, y)
ax3 = plt.subplot2grid((2, 2), (1, 1), colspan=1, rowspan=1)
ax3.plot(x, y)
plt.show()
或者
def func83():
x = [0, 1, 2]
y = [0, 1, 2]
# 定义figure
plt.figure()
# 分隔figure
gs = gridspec.GridSpec(2, 3)
ax1 = plt.subplot(gs[0, :])
ax1.plot(x, y)
ax2 = plt.subplot(gs[1, 0:2])
ax2.plot(x, y)
ax3 = plt.subplot(gs[1, 2])
ax3.plot(x, y)
plt.show()
8.3、figure图的嵌套
def func84():
# 定义figure
fig = plt.figure()
# 定义数据
x = np.linspace(0, np.pi * 2, 100)
y = np.sin(x)
# figure的百分比, 从figure 10%的位置开始绘制, 宽高是figure的80%
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
# 获得绘制的句柄
ax1 = fig.add_axes([left, bottom, width, height])
# 绘制点(x,y)
ax1.plot(x, y, 'r')
# 嵌套方法一
# figure的百分比, 从figure 10%的位置开始绘制, 宽高是figure的80%
left, bottom, width, height = 0.15, 0.15, 0.25, 0.25
# 获得绘制的句柄
ax2 = fig.add_axes([left, bottom, width, height])
# 绘制点(x,y)
ax2.plot(x, y, 'r')
# 嵌套方法二
left, bottom, width, height = 0.6, 0.6, 0.25, 0.25
plt.axes([left, bottom, width, height])
plt.plot(x, y, 'r')
plt.show()
9、3D绘制
def func9():
# 定义figure
fig = plt.figure()
# 将figure变为3d
ax = Axes3D(fig)
# 数据数目
n = 400
# 定义x, y
x = np.arange(-4, 4, 0.2)
y = np.arange(-4, 4, 0.2)
# 生成网格数据
X, Y = np.meshgrid(x, y)
# 计算每个点对的长度
R = np.sqrt(X ** 2 + Y ** 2)
# 计算Z轴的高度
Z = np.sin(R)
# 绘制3D曲面
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
# 绘制从3D曲面到底部的投影
ax.contour(X, Y, Z, zdim='z', offset=-2, cmap='rainbow')
# 设置z轴的维度
ax.set_zlim(-2, 2)
plt.show()