matplotlib 安装Anaconda安装
pip安装
matplotlib 基本使用基本用法
figure 图像
设置坐标轴1
设置坐标轴2
Legend 图例
Annotation 标注
tick 能见度
基本用法figure():定义图像窗口
plot():画曲线
show():显示图像
参考代码:import matplotlib.pyplot as pltimport numpy as np# 使用np.linspace定义x:范围是(-1,1);个数是50. 仿真一维数据组(x ,y)表示曲线1.x = np.linspace(-1, 1, 50)
y = 2*x + 1# 使用plt.figure定义一个图像窗口. 使用plt.plot画(x ,y)曲线. 使用plt.show显示图像plt.figure()
plt.plot(x, y)
plt.show()
img1
figure 图像简单显示图像
参考代码:import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1y2 = x**2plt.figure()
plt.plot(x, y1)
plt.show()
img1# 使用plt.figure定义一个图像窗口:编号为3;大小为(8, 5).plt.figure(num=3, figsize=(8, 5),)
plt.plot(x, y2)# 使用plt.plot画(x ,y1)曲线,曲线的颜色属性(color)为红色;曲线的宽度(linewidth)为1.0;plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')# 曲线的类型(linestyle)为虚线. 使用plt.show显示图像.plt.show()
img2
设置坐标轴1xlim():设置x坐标轴范围
ylim():设置y坐标轴范围
xlabel():设置x坐标轴名称
ylabel():设置y坐标轴名称
xticks():设置x轴刻度
yticks():设置y轴刻度
参考代码:import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1y2 = x**2plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
plt.xlabel('I am x')
plt.ylabel('I am y')
plt.show()
img1new_ticks = np.linspace(-1, 2, 5)
print(new_ticks)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])
plt.show()
img2
设置坐标轴2gca():获取当前坐标轴信息
.spines:设置边框
.set_color:设置边框颜色:默认白色
.spines:设置边框
.xaxis.set_ticks_position:设置x坐标刻度数字或名称的位置
.yaxis.set_ticks_position:设置y坐标刻度数字或名称的位置
.set_position:设置边框位置
设置不同名字和位置:import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1y2 = x**2plt.figure()
plt.plot(x, y2)
plt.plot(x, y1, color='red', linewidth=1.0, linestyle='--')
plt.xlim((-1, 2))
plt.ylim((-2, 3))
new_ticks = np.linspace(-1, 2, 5)
plt.xticks(new_ticks)
plt.yticks([-2, -1.8, -1, 1.22, 3],['$really\ bad$', '$bad$', '$normal$', '$good$', '$really\ good$'])
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
plt.show()
img1
调整坐标轴:ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
plt.show()
img2ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data',0))
plt.show()
img3
Legend 图例添加图例
调整位置和名称
添加图例:import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(-3, 3, 50)
y1 = 2*x + 1y2 = x**2plt.figure()#set x limitsplt.xlim((-1, 2))
plt.ylim((-2, 3))# set new sticksnew_sticks = np.linspace(-1, 2, 5)
plt.xticks(new_sticks)# set tick labelsplt.yticks([-2, -1.8, -1, 1.22, 3],
[r'$really\ bad$', r'$bad$', r'$normal$', r'$good$', r'$really\ good$'])# set line sylesl1, = plt.plot(x, y1, label='linear line')
l2, = plt.plot(x, y2, color='red', linewidth=1.0, linestyle='--', label='square line')
plt.legend(loc='upper right')
img1
调整位置和名称:plt.legend(handles=[l1, l2], labels=['up', 'down'], loc='best')
img2
Annotation 标注annotate:添加注释
text:添加注释
参考代码:import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(-3, 3, 50)
y = 2*x + 1plt.figure(num=1, figsize=(8, 5),)
plt.plot(x, y,)
img1# 移动坐标ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
img2x0 = 1
y0 = 2*x0 + 1
plt.plot([x0, x0,], [0, y0,], 'k--', linewidth=2.5)# set dot stylesplt.scatter([x0, ], [y0, ], s=50, color='b')
img3# 添加注释 annotateplt.annotate(r'$2x+1=%s$' % y0, xy=(x0, y0), xycoords='data', xytext=(+30, -30),
textcoords='offset points', fontsize=16,
arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
img4# 添加注释 text plt.text(-3.7, 3, r'$This\ is\ the\ some\ text. \mu\ \sigma_i\ \alpha_t$',
fontdict={'size': 16, 'color': 'r'})
img5
tick 能见度调整坐标
生成图形:import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(-3, 3, 50)
y = 0.1*x
plt.figure()# 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序plt.plot(x, y, linewidth=10, zorder=1)
plt.ylim(-2, 2)
ax = plt.gca()
ax.spines['right'].set_color('none')
ax.spines['top'].set_color('none')
ax.spines['top'].set_color('none')
ax.xaxis.set_ticks_position('bottom')
ax.spines['bottom'].set_position(('data', 0))
ax.yaxis.set_ticks_position('left')
ax.spines['left'].set_position(('data', 0))
img1
调整坐标:for label in ax.get_xticklabels() + ax.get_yticklabels():
label.set_fontsize(12) # 在 plt 2.0.2 或更高的版本中, 设置 zorder 给 plot 在 z 轴方向排序
label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))
plt.show()
img2
画图种类Scatter 散点图
Bar 柱状图
Contours 等高线图
Image 图片
3D 数据Scatter 散点图scatter:绘制散点图
参考代码:import matplotlib.pyplot as pltimport numpy as np
n = 1024 # data sizeX = np.random.normal(0, 1, n) # 每一个点的X值Y = np.random.normal(0, 1, n) # 每一个点的Y值T = np.arctan2(Y,X) # for color valueplt.scatter(X, Y, s=75, c=T, alpha=.5)
plt.xlim(-1.5, 1.5)
plt.xticks(()) # ignore xticksplt.ylim(-1.5, 1.5)
plt.yticks(()) # ignore yticksplt.show()
img1Bar 柱状图bar():生成柱状图
生成基本图形:import matplotlib.pyplot as pltimport numpy as np
n = 12X = np.arange(n)
Y1 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
Y2 = (1 - X / float(n)) * np.random.uniform(0.5, 1.0, n)
plt.bar(X, +Y1)
plt.bar(X, -Y2)
plt.xlim(-.5, n)
plt.xticks(())
plt.ylim(-1.25, 1.25)
plt.yticks(())
plt.show()
img1
加颜色和数据:plt.bar(X, +Y1, facecolor='#9999ff', edgecolor='white')
plt.bar(X, -Y2, facecolor='#ff9999', edgecolor='white')
img2for x, y in zip(X, Y1): # ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, y + 0.05, '%.2f' % y, ha='center', va='bottom')for x, y in zip(X, Y2): # ha: horizontal alignment
# va: vertical alignment
plt.text(x + 0.4, -y - 0.05, '%.2f' % y, ha='center', va='top')
img3Contours 等高线图meshgrid:在二维平面中将每一个x和每一个y分别对应起来,编织成栅格
contour:绘制等高线
画等高线:import matplotlib.pyplot as pltimport numpy as npdef f(x,y):
# the height function
return (1 - x / 2 + x**5 + y**3) * np.exp(-x**2 -y**2)
n = 256x = np.linspace(-3, 3, n)
y = np.linspace(-3, 3, n)
X,Y = np.meshgrid(x, y)# use plt.contourf to filling contours# X, Y and value for (X,Y) pointplt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.hot)# use plt.contour to add contour linesC = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)
img1
添加高度数字:plt.clabel(C, inline=True, fontsize=10)
plt.xticks(())
plt.yticks(())
img2Image 图片imshow:显示图片
colorbar:添加颜色图例
参考代码:import matplotlib.pyplot as pltimport numpy as np
a = np.array([0.313660827978, 0.365348418405, 0.423733120134, 0.365348418405, 0.439599930621, 0.525083754405, 0.423733120134, 0.525083754405, 0.651536351379]).reshape(3,3)
plt.imshow(a, interpolation='nearest', cmap='bone', origin='lower')
plt.colorbar(shrink=.92)
plt.xticks(())
plt.yticks(())
plt.show()
img13D 数据3D 图
投影
3D 图:import numpy as npimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import Axes3D
fig = plt.figure()
ax = Axes3D(fig)
img1# X, Y valueX = np.arange(-4, 4, 0.25)
Y = np.arange(-4, 4, 0.25)
X, Y = np.meshgrid(X, Y) # x-y 平面的网格R = np.sqrt(X ** 2 + Y ** 2)# height valueZ = np.sin(R)
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
跨度1
img2
跨度5
img3
投影:ax.contourf(X, Y, Z, zdir='z', offset=-2, cmap=plt.get_cmap('rainbow'))
xz平面投影
img4
xy平面投影
img5
多图合并显示Subplot 多合一显示
Subplot 分格显示
图中图
次坐标轴
Subplot 多合一显示均匀图中图
不均匀图中图
均匀图中图:import matplotlib.pyplot as pltplt.figure()plt.subplot(2,2,1)plt.plot([0,1],[0,1])plt.subplot(2,2,2)plt.plot([0,1],[0,2])plt.subplot(223)plt.plot([0,1],[0,3])plt.subplot(224)plt.plot([0,1],[0,4])plt.show() # 展示
作者:CrazyWolf_081c
链接:https://www.jianshu.com/p/4e16c41b195f