python之matplotlib绘图功能介绍
前言:
本文将matplotlib包中最基础的绘图功能写为几个Deme,以便对该包绘图功能加以理解。如果熟悉matlab的同学,可以很快学到这个包的绘图功能,因为,这个包的绘图功能代码和matlab的绘图几乎是一样的,差别很少。本文会给出11个基本绘图Demo,每个Demo都有较详细的代码注释,了解这些Demo后,应该可以解决大多数的绘图问题。
Demo目录
一、plot基础用法
二、Figure图像
三、gca设置坐标轴
四、legend图例
五、annotate图像标注
六、scatter散点图
七、bar直方图
八、contours等高线图
九、3D图
十、subplot子图像
十一、动态图
一、plot基础用法
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 100)
y = 2*x + 1
plt.plot(x, y)
plt.show()
执行图
二、Figure图像
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 100)
y1 = 2 * x + 1
y2 = x**2
# 创建图形
plt.figure()
plt.plot(x, y1)
# 创建图形
plt.figure()
plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--')
# 绘制在一个图形中
plt.figure()
plt.plot(x, y1, color='blue', linewidth=1.0, linestyle='-')
plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--')
plt.show()
执行图
三、设置坐标轴
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y1 = 2 * x + 1
y2 = x**2
plt.figure()
# 限制xy的范围
plt.xlim(-1, 2)
plt.ylim(-2, 3)
# xy描述
plt.xlabel('I am x')
plt.ylabel('I am y')
# xy尺度标签
new_ticks = np.linspace(-2, 2, 11)
plt.xticks(new_ticks)
plt.yticks([-1, 0, 1, 2, 3],
['level-1', 'level0', 'level1', 'level2', 'level3'])
# 获取当前坐标轴 gca get curren axis
ax = plt.gca()
# 把右边和上边的边框去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 把x轴的刻度设置为'bottom'
ax.xaxis.set_ticks_position('bottom')
# 把y轴的刻度设置为'left'
ax.yaxis.set_ticks_position('left')
# 平移下边的边框至y=0的位置
ax.spines['bottom'].set_position(('data', 0))
# 平移左边的边框至x=0的位置
ax.spines['left'].set_position(('data', 0))
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.plot(x, y2, color='blue', linewidth=3.0, linestyle='-')
plt.show()
执行图
四、legend图例
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-3, 3, 100)
y1 = 2 * x + 1
y2 = x**2
plt.figure()
line1, = plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
line2, = plt.plot(x, y2, color='blue', linewidth=3.0, linestyle='-')
print(type(line2))
plt.legend(handles=[line1, line2], labels=['test1', 'test2'], loc='best')
plt.show()
执行图
五、annotate图像标注
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-1, 1, 100)
y1 = 2 * x + 1
# 获取当前坐标轴 gca get curren axis
ax = plt.gca()
# 把右边和上边的边框去掉
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
# 把x轴的刻度设置为'bottom'
ax.xaxis.set_ticks_position('bottom')
# 把y轴的刻度设置为'left'
ax.yaxis.set_ticks_position('left')
# 平移下边的边框至y=0的位置
ax.spines['bottom'].set_position(('data', 0))
# 平移左边的边框至x=0的位置
ax.spines['left'].set_position(('data', 0))
# 画点
x0 = 0.5
y0 = 2 * 0.5 + 1
plt.scatter(x0, y0, s=50, color='b')
# 画虚线
plt.plot([x0, x0], [y0, 0], 'k--', lw=1)
# 画弧线标注
plt.annotate(r'$2x + 1 = %s$' % y0, xy=(x0, y0), xytext=(+30, -30), textcoords='offset points',
fontsize=16, arrowprops=dict(arrowstyle='->', connectionstyle='arc3,rad=.2'))
# 显示文字
plt.text(-1, 2, r'$This\ is\ the\ text$', fontdict={'size': '16', 'color': 'r'})
# 画线
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='-')
plt.show()
执行图
六、scatter散点图
import matplotlib.pyplot as plt
import numpy as np
x = np.random.normal(0, 1, 500)
y = np.random.normal(0, 1, 500)
# 绘制散点图
plt.scatter(x, y, s=50, c='b', alpha=0.5)
# 限制大小
plt.xlim((-3, 3))
plt.ylim((-3, 3))
# 去掉刻度
plt.xticks(())
plt.yticks(())
# 显示图形
plt.show()
执行图
七、bar直方图
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = 2**x + 10
# 画柱状图
plt.bar(x, y, facecolor='#9999ff', edgecolor='white')
# 添加文字
for x, y in zip(x, y): # zip可以把变量对应打包起来,这样可以一次遍历所有变量
plt.text(x, y, r'%.2f' % y, ha='center', va='bottom')
plt.show()
执行图
八、contours等高线图
import matplotlib.pyplot as plt
import numpy as np
def height(px, py):
return (1 - px / 2 + px**5 + py**3) * np.exp(-px**2 - py**2)
x = np.linspace(-3, 3, 100)
y = np.linspace(-3, 3, 100)
# 格网化
X, Y = np.meshgrid(x, y)
# 画等高线图
plt.contourf(X, Y, height(X, Y), 8, alpha=0.75, cmap=plt.cm.hot) # 参数中的8代表等高线的条数为8+1=9条
# 画等高线
C = plt.contour(X, Y, height(X, Y), colors='black', linewidths=.5)
# 等高线标注
plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
plt.show()
执行图
九、3D图
import matplotlib.pyplot as plt
import numpy as np
from mpl_toolkits.mplot3d import Axes3D
# 创建图像
fig = plt.figure()
# 图像加入3D视图中
ax = Axes3D(fig)
# 数据(3维坐标点X,Y,Z)准备
x = np.arange(-4, 4, 0.25)
y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(x, y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
# 绘制3D图
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow')) # 其中rstride是行步长(row stride),cstride是列步长(column stride)
# 绘制3D图映射的二维等高线图
ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap='rainbow') # 映射方向为z,位置偏移至-2处,颜色为彩虹色
ax.set_zlim(-2, 2) # 设置z轴的刻度限制为-2到2
plt.show()
执行图
十、subplot子图像
import matplotlib.pyplot as plt
# 创建图像
plt.figure()
plt.subplot(2, 2, 1) # 将图像分为2行2列,4个子图像,这是第1行1列的一个子图像
plt.plot([0, 1], [0, 1])
plt.subplot(2, 2, 2) # 将图像分为2行2列,4个子图像,这是第1行2列的一个子图像
plt.plot([0, 1], [0, 1])
plt.subplot(2, 2, 3) # 将图像分为2行2列,4个子图像,这是第2行1列的一个子图像
plt.plot([0, 1], [0, 1])
plt.subplot(2, 2, 4) # 将图像分为2行2列,4个子图像,这是第2行2列的一个子图像
plt.plot([0, 1], [0, 1])
# 创建子图像大小不一致的方法
plt.figure()
plt.subplot(2, 1, 1) # 将图像分为2行1列,2个子图像,这是第1行1列的一个子图像
plt.plot([0, 1], [0, 1])
plt.subplot(2, 3, 4) # 将图像分为2行3列,6个子图像,这是第2行1列的一个子图像(因为第一行的3个子图像被一个图像占满,因此这个是第4个子图像)
plt.plot([0, 1], [0, 1])
plt.subplot(2, 3, 5) # 将图像分为2行3列,6个子图像,这是第2行2列的一个子图像
plt.plot([0, 1], [0, 1])
plt.subplot(2, 3, 6) # 将图像分为2行3列,6个子图像,这是第2行3列的一个子图像
plt.plot([0, 1], [0, 1])
plt.show()
执行图
十一、动态图
import matplotlib.pyplot as plt
import numpy as np
from matplotlib import animation
fig, ax = plt.subplots()
x = np.arange(0, 2*np.pi, 0.01)
line, = ax.plot(x, np.sin(x))
def animate(i):
line.set_ydata(np.sin(x+i/10))
return line,
def init():
line.set_ydata(np.sin(x))
return line,
ani = animation.FuncAnimation(fig, func=animate, init_func=init, interval=20)
plt.show()
执行图