【Matplotlib】Matplotlib基础知识笔记

基本要点

折线图:准备所有的x和所有的y

传入即可:

plt.plot(x,y,label)
#x和y是列表类型,label是该组映射的标签
plt.legend() #绘制图例 , 上述label需要结合legend使用
#再添加一次plot就可以再设置一组xy映射
#x有多大,y就有多大
#下面每种画图方式都是如此,在x对应的位置绘制y相关的图像

不需要将x和y一个一个的匹配成元组

1. 导入模块:
import matplotlib.pyplot as plt

2. 定义图像窗口:
plt.figure(num,figsize,dpi) #设置 窗口 大小,figsize大小,dpi分辨率

3. 画图:
plt.plot(x, y,color,linewidth,linestyle,label)

4. 定义坐标轴范围:
plt.xlim(n1,n2)/plt.ylim()

5. 设置描述信息:
plt.xlabel("xxx")/plt.ylabel()
plt.title()

6. 定义坐标轴刻度及名称:
plt.xticks()/plt.yticks()
plt.xticks(ticks,[lables,...]) 
#设置刻度,指示刻度的是ticks,label是ticks的标签,类似别		 名,rotation旋转,两个参数都是列表类型,如:
plt.yticks([-2, -1.8, -1, 1.22, 3],['really bad', 'bad', 'normal', 'good', 'really good'])
#传入()的时候,隐藏刻度

7. 设置图像边框颜色:
ax = plt.gca()  #获取当前坐标轴的信息
ax.spines['top,bottom,left,right'].set_color('颜色或none')

8. 调整 刻度 位置:
ax.xaxis.set_ticks_position() #top,bottom,both,default,none
ax.yaxis.set_ticks_position()

9. 调整 边框(坐标轴) 位置:
ax.spines['top,bottom,left,right'].set_position((prop,num)) #prop为outward,axes,data

10.保存图片
plt.savefig("path") #保存图片

11.网格
plt.grid(alpha=0.1) #网格,根据刻度进行绘制。alpha设置透明度,从0到1

12.添加标注
plt.annotate('注解内容', xy=(x0, y0), xycoords='data', xytext=(+30, -30),
             textcoords='offset points', fontsize=16,
             arrowprops=dict(arrowstyle='->', connectionstyle="arc3,rad=.2"))
#xy:对哪个点标注
#xycoords:基于什么来选择 被标注物体 的位置
#xytext:标注的位置
#textcoords:基于什么来选择 标注 的位置
#arrowprops:设置箭头类型和箭头弧度,类型为dict

13.添加注释
plt.text(x, y, '注释内容',fontdict={
    
    'size': 16, 'color': 'r'})
#x,y注释的位置
#fontdict:dict类型,注释的信息

在这里插入图片描述

14.设置tick的能见度
for label in ax.get_xticklabels() + ax.get_yticklabels(): #取出label
    label.set_fontsize(12) #设置label
    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.7, zorder=2))

散点图、直方图、柱形图

散点图

plt.scatter(x,y,label)

直方图

绘制连续的数据:某个区间的数量、频率、分布

plt.hist(data,num,density) 
#data表示数据,num表示将data分成几组,直方图的高度就是每组的数量
#density 为True时,每组的数量变成频率,也就是占比

柱形图

绘制离散的数据:每个种类的数量和频率

plt.bar(x,y,width,facecolor,edgecolor) #纵向,width设置柱子宽度,0到1
#x代表柱子的位置,y代表柱子的高度
#y可以写成+y或-y,可以实现向上的柱子,和向下的柱子
plt.barh(x,y,height) #横向
1.柱子上加数据
for x, y in zip(X, Y1):
    plt.text(x, y , '%.2f' % y, ha='center', va='bottom')
    #对x和y,加上'%.2f' % y
    #ha:横向对齐方式 horizontal alignment
    #va:纵向对齐方式 vertical alignment

等高线图

三维,包括:x,y,height=f(x,y)

1.颜色填充
plt.contourf(X, Y, f(X, Y), 8, alpha=.75, cmap=plt.cm.RdBu)
#8表示密集程度:0-10
#cmap:color map
https://matplotlib.org/examples/color/colormaps_reference.html #color map
    
2.等高线绘制
C = plt.contour(X, Y, f(X, Y), 8, colors='black', linewidth=.5)

3.添加高度数字
plt.clabel(C, inline=True, fontsize=10)
#inline:是否把label放在线中

在这里插入图片描述

多图合并显示

子图

subplot

1.子图
plt.figure()
plt.subplot(2,2,1) #把整个图,分成2行2列,当前为第一个
plt.plot([0,1],[0,1]) #在当前子图中绘制

2.不均匀子图
plt.subplot(2,1,1)
plt.plot([0,1],[0,1])

plt.subplot(2,3,4)
plt.plot([0,1],[0,2])

在这里插入图片描述

更加方便的分图:

subplot2grid

ax1 = plt.subplot2grid((3, 3), (0, 0), colspan=3,rowspan)
#(3, 3):分成3行3列
#(0, 0):从第0行第0列开始画
#colspan,rowspan:列行的跨度,默认为1
ax1.plot([1, 2], [1, 2])    # 画小图
ax1.set_title('ax1_title')  # 设置小图的标题

gridspec

import matplotlib.gridspec as gridspec

plt.figure(figsize=(8, 8))
gs = gridspec.GridSpec(3, 3) #整个图像窗口分成3行3列

#使用plt.subplot来作图
ax6 = plt.subplot(gs[0, :]) #gs[0, :]表示这个图占第0行和所有列
ax7 = plt.subplot(gs[1, :2]) #gs[1, :2]表示这个图占第1行和第2列前的所有列
ax8 = plt.subplot(gs[1:, 2]) #gs[1:, 2]表示这个图占第1行后的所有行和第2列
ax9 = plt.subplot(gs[-1, 0]) #gs[-1, 0]表示这个图占倒数第1行和第0列
ax10 = plt.subplot(gs[-1, -2]) # gs[-1, -2]表示这个图占倒数第1行和倒数第2列

在这里插入图片描述

subplots

f, ((ax11, ax12), (ax13, ax14)) = plt.subplots(2, 2, sharex=True, sharey=True)
#分成2行2列
#sharex:共享x轴坐标
#返回值:窗口,以及所有子图

plt.tight_layout() #表示紧凑显示图像

图中图

窗口>大图>小图

1.设置窗口
fig = plt.figure()

2.画大图
left, bottom, width, height = 0.1, 0.1, 0.8, 0.8
ax1 = fig.add_axes([left, bottom, width, height])
#设置大图在窗口中的位置:百分比
ax1.plot(x, y, 'r')

3.画小图
#步骤与画大图一样
left, bottom, width, height = 0.2, 0.6, 0.25, 0.25
ax2 = fig.add_axes([left, bottom, width, height])
ax2.plot(y, x, 'b')

次坐标轴

fig, ax1 = plt.subplots()
ax2 = ax1.twinx() #镜面

ax1.plot(x, y1, 'g-')   
ax1.set_xlabel('X data')
ax1.set_ylabel('Y1 data', color='g')
ax2.plot(x, y2, 'b-') 
ax2.set_ylabel('Y2 data', color='b')

在这里插入图片描述

3D作图、动画

3D

from mpl_toolkits.mplot3d import Axes3D

1.设置窗口
fig = plt.figure()
ax = Axes3D(fig) #在窗口中 添加3D坐标轴

2.作3D表面
ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.get_cmap('rainbow'))
#rstide,cstride:表示row和col的跨度,跨度越小,网格越密集

在这里插入图片描述

3.投影
ax.contourf(X, Y, Z, zdir='z', offset=-1, cmap=plt.get_cmap('rainbow'))
#zdir:z表示对XY投影,x表示对YZ投影
#offset:投影面的偏移坐标

动画

1.设置函数,添加线条
line, = ax.plot(x, np.sin(x))

2.定义函数:动画、初始
def animate(i):
    line.set_ydata(np.sin(x + i/10.0))
    return line,
def init():
    line.set_ydata(np.sin(x))
    return line,

3.将窗口信息、函数信息等 添加到animation的参数中
ani = animation.FuncAnimation(fig=fig,
                              func=animate,
                              frames=100,
                              init_func=init,
                              interval=20,
                              blit=True)

参考

部分参考链接丢失(真的丢失),如有侵权,请联系我删除

猜你喜欢

转载自blog.csdn.net/qq_41340996/article/details/124737884