共12个章节,
本文为第1~4章节。
❤️ 本文速 览
目录 1 准备工作1.1 Matplotlib安装1.2 Matplotlib版本查看1.3 Matplotlib默认参数设置2 、散点图2.1 默认散点图2.2 散点图点大小、颜色设置2.3 散点图标记、点动态变化2.4 散点图colormap、透明度设置3 、折线图3.1 默认折线图3.2 折线图线型、分面设置3.3 折线图线宽设置 3.4 折线图标记设置3.5 折线图多标记、标记间距设置3.6 折线图误差线设置3.7 折线图仅保留误差线3.8 折线图填充设置3.9 折线图添加垂直线3.10 折线图添加垂直平面4 、直方图4.1 默认直方图4.2 直方图bins数设置4.3 直方图配色、轴范围设置4.4 水平直方图 4.5 直方图bins添加边界线 4.6 多组直方图 4.7 直方图修改箱子透明度4.8 更多组直方图 4.9 2 D直方图 4.10 2 D直方图修改bins数4.11 2 D直方图定义colormap4.12 2 D直方图显示范围内变量 4.13 边界直方图
1 准备工作 1.1 Matplotlib安装#方法1 使用pip安装 pip install matplotlib#方法2 使用conda安装 conda install matplotlib
1.2 Matplotlib版本查看Matplotlib版本查看,
# matplotlib版本查看 pip show matplotlib
本文使用的是Matplotlib 3.6.2版本。
1.3 Matplotlib默认参数设置# 默认参数设置 import matplotlib.pyplot as plt plt.rcParams['font.size' ] = 15 #设置字号 plt.rcParams['font.family' ] = 'serif' #设置字体 tdir = 'out' major = 5.0 minor = 3.0 plt.rcParams['xtick.direction' ] = tdir #x轴刻度线朝外,PS刻度线为数字与坐标轴之间的连线 plt.rcParams['ytick.direction' ] = tdir #y轴刻度线朝外 plt.rcParams['xtick.major.size' ] = major #x轴主刻度线长度 plt.rcParams['xtick.minor.size' ] = minor #x轴副刻度线长度 plt.rcParams['ytick.major.size' ] = major #y轴主刻度线长度 plt.rcParams['ytick.minor.size' ] = minor #y轴副刻度线长度
默认参数设定后,后续绘图涉及以上参数的地方都采用此处值。
2、散点图 该部分通过散点图介绍Matplotlib使用。
2.1 默认散点图绘图数据准备,
#准备绘图数据 import numpy as np # 导入依赖numpy import matplotlib.pyplot as plt #导入matplotlib N = 50 x = np.linspace(0. , 10. , N) #x变量数据:使用numpy生成长度为50的数组,范围在1~10之间 y = np.sin(x)**2 + np.cos(x) #y变量数据:基与x生成y
x,y变量预览,
plt.figure() #figure生成一幅Figure plt.scatter(x, y) #scatter函数绘制散点图
2.2 散点图点大小、颜色设置下面对点大小固定变化、颜色、图例进行调整以美化图形,
plt.figure() plt.scatter(x, y, s=15 , label=r'$ y = sin^2(x) + cos(x), color=' r') #s设置点的大小 #label设置图例名称 #color设置点颜色 plt.axis(' equal') #x轴和y轴单位长度相同。还有一个plt.axis(' square')将x轴和y轴长度设置相等,即图是正方形。 plt.legend() # 开启图例 plt.xlabel(r' $x$ (rad)') # 设置x轴标题 plt.ylabel(r' $y) # 设置y轴标题 plt.show() #图形渲染/展示
2.3 散点图标记、点动态变化设置图形分辨率、点marker、点大小动态变化,更多marker修改👉一文掌握marker使用
plt.figure(dpi=100 ) #设置图形分辨率,控制图形清晰度 plt.scatter( x, y, s=x, #点大小随变量x大小变化 marker='^' , #设置点的marker为三角形 label=r'$ y = sin^2(x) + cos(x), color=' r') plt.axis(' equal') plt.legend() plt.xlabel(r' $x$ (rad)') plt.ylabel(r' $y) plt.show()
2.4 散点图colormap、透明度设置设置点颜色动态变化、设置点colormap、透明度,了解详细颜色设置👉Python可视化调色盘colormap
from matplotlib import cm plt.figure(dpi=150 ) plt.scatter( x, y, s=x, c=x, #点颜色随变量x大小变化 marker='^' , label=r'$ y = sin^2(x) + cos(x), alpha=.8, #设置点透明度 cmap=cm.get_cmap(' Blues')) #设置colormap plt.axis(' equal') plt.legend() plt.xlabel(r' $x$ (rad)') plt.ylabel(r' $y) plt.colorbar() #添加colorbar plt.show()
3、折线图 该部分通过折线图介绍Matplotlib使用。
3.1 默认折线图#准备绘图数据 N = 50 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x)#散点图绘制 plt.plot(x, y) plt.show()
3.2 折线图线型、分面设置修改折线图线型、分面展示,
N = 50 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) rows = 2 columns = 2 grid = plt.GridSpec(rows, columns, wspace=.25 , hspace=.25 )#分面为4张图展示不同线型,分面此处使用GridSpec()方法 #还可以使用subplot()、add_subplot()方法 linestyles = ['-' , '--' , '-.' , ':' ] plt.figure(dpi=120 )for i in range(len(linestyles)): plt.subplot(grid[i]) plt.plot( x, y, linestyle=linestyles[i], #linestyle设置线型 label=r'$ y = sin^2(x) + cos(x)) plt.axis(' equal') plt.xlabel(' $x$ (rad)') plt.legend() #添加文字注释 plt.annotate('linestyle ' ' + str(linestyles[i]) + ' '', xy=(0.5, -2.5), va=' center', ha=' left')
3.3 折线图线宽设置修改折线图线宽,
N = 50 rows = 2 columns = 2 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) grid = plt.GridSpec(rows, columns, wspace=.25 , hspace=.25 ) linewidth = [2 , 3 , 4 , 5 ] plt.figure(dpi=150 )for i in range(len(linestyles)): plt.subplot(grid[i]) plt.plot( x, y, linestyle='-.' , lw=linewidth[i], #lw设置线宽 label=r'$ y = sin^2(x) + cos(x)) plt.axis(' equal') plt.xlabel(' $x$ (rad)') plt.legend() plt.annotate('linewidth ' + str(linewidth[i]), xy=(0.5, -2.5), va=' center', ha=' left')
3.4 折线图标记设置折线图添加marker,
N = 50 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) plt.figure(dpi=150 ) plt.plot( x, y, 'o' , ls='-.' , lw=2 , ms=7 , #marker大小 markevery=12 , #每隔12个点添加marker label=r'$ y = sin^2(x) + cos(x)) plt.axis(' equal') plt.xlabel(' $x$ (rad)') plt.legend() plt.annotate('markevery: 5', xy=(0.5, -2.5), va=' center', ha=' left')
3.5 折线图多标记、标记间距设置不同折线图添加不同marker、按照不同的间距,
N = 50 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) rows = 2 columns = 2 grid = plt.GridSpec(rows, columns, wspace=.25 , hspace=.25 ) mark = [5 , 8 , 13 , 15 ] color = ['#00429d' , '#627c94' , '#f4777f' , '#93003a' ] plt.figure(dpi=150 )for i in range(len(linestyles)): plt.subplot(grid[i]) plt.plot( x, y, 'o' , ls='-.' , lw=2 , ms=8 , markevery=mark[i], #不同间隔 color=color[i], #不同颜色 label=r'$ y = sin^2(x) + cos(x)) plt.axis(' equal') plt.annotate('markevery: ' + str(mark[i]), xy=(0.5, -2.5), va=' center', ha=' left') plt.xlabel(' $x$ (rad)') plt.legend()
3.6 折线图误差线设置折线图添加误差线,
N = 25 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) np.random.seed(100 ) noise_x = np.random.random(N) * .2 + .1 noise_y = np.random.random(N) * .7 + .4 plt.figure(dpi=120 )#使用errorbar方法添加误差线 plt.errorbar( x, y, yerr=noise_y, #y轴方向添加误差线 xerr=noise_x, #x轴方向添加误差线 label=r'$ y = sin^2(x) + cos(x)) plt.axis(' equal') plt.legend() plt.xlabel(' $x$ (rad)')
3.7 折线图仅保留误差线去掉折线,只保留误差线,
N = 25 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) np.random.seed(100 ) noise_x = np.random.random(N) * .2 + .1 noise_y = np.random.random(N) * .7 + .4 plt.figure(dpi=150 ) plt.errorbar( x, y, xerr=noise_x, yerr=noise_y, label=r'$ y = sin^2(x) + cos(x), color=' r', #marker颜色 fmt=' o', #marker形状 ecolor=' blue', #误差线颜色 ) plt.axis(' equal') plt.legend() plt.xlabel(' $x$ (rad)')
3.8 折线图填充设置折线图区域填充,
N = 25 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) np.random.seed(100 ) noise = np.random.random(N) * .7 + .4 plt.figure(dpi=120 ) plt.plot(x, y, ls='-' , label=r'$ y = sin^2(x) + cos(x)) #使用fill_between方法 plt.fill_between( x, y + noise, #y轴上方区域 y - noise, #y轴下方区域 alpha=.3) plt.axis(' equal') plt.legend() plt.xlabel(' $x$ (rad)')
3.9 折线图添加垂直线添加x轴、y轴方向垂直线,
N = 25 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) np.random.seed(100 ) noise = np.random.random(N) * .7 + .4 plt.figure(dpi=120 ) plt.plot(x, y, ls='-' , label=r'$ y = sin^2(x) + cos(x), color=' darkgreen') plt.fill_between(x, y + noise, y - noise, color=' darkgreen', alpha=.3) plt.axis(' equal') #hlines绘制水品线 plt.hlines( 0, #y轴位置 xmin=0, #x轴起始位置 xmax=10, #x轴终止位置 ls=' --', #线型 color=' red', #线颜色 label=' hlines') #图例 #hlines绘制垂直线 plt.vlines(2, ymin=-3, ymax=3, ls=' --', color=' blue', label=' vlines') plt.legend() plt.xlabel(' $x$ (rad)')
3.10 折线图添加垂直平面添加y轴方向垂直平面,
N = 25 x = np.linspace(0. , 10. , N) y = np.sin(x)**2 + np.cos(x) np.random.seed(100 ) noise = np.random.random(N) * .7 + .4 plt.figure(dpi=120 ) plt.plot(x, y, ls='-' , label=r'$ y = sin^2(x) + cos(x), color=' darkgreen') plt.fill_between(x, y + noise, y - noise, color=' darkgreen', alpha=0.3) plt.axis(' equal') plt.fill_between((2, 4), -3.2, 3.2, facecolor=' blue', alpha=0.3) plt.xlim(0, 10) plt.ylim(-3, 3) plt.legend() plt.xlabel(' $x$ (rad)')
4、直方图 该部分通过直方图介绍Matplotlib使用。
4.1 默认直方图N = 1000 np.random.seed(10021 ) x = np.random.randn(N) * 2 + 15 plt.hist(x)
默认分箱bins为10个。
4.2 直方图bins数设置修改分箱bins数目。
N = 1000 np.random.seed(10021 ) x = np.random.randn(N) * 2 + 15 plt.figure(dpi=120 ) plt.hist( x, bins=40 , #设置bins数目为40个 label=r'$\mu = 15, \sigma = 2 #添加图例 ) plt.legend()
4.3 直方图配色、轴范围设置修改配色、横轴显示范围。
N = 1000 np.random.seed(10021 ) x = np.random.randn(N) * 2 + 15 plt.figure(dpi=120 ) plt.hist(x, bins=40 , range=(12 , 18 ),#设置横轴显示范围 color='pink' , #修改配色 label=r'$\mu = 15, \sigma = 2) plt.legend()
4.4 水平直方图绘制水平方向直方图。
N = 1000 np.random.seed(10021 ) x = np.random.randn(N) * 2 + 15 plt.figure(dpi=120 ) plt.hist( x, bins=25 , range=(12 , 18 ), color='royalblue' , orientation='horizontal' , #水平方向直方图 label=r'$\mu = 15, \sigma = 2) plt.legend()
4.5 直方图bins添加边界线为直方图bins添加边界线。
N = 1000 np.random.seed(10021 ) x = np.random.randn(N) * 2 + 15 plt.figure(dpi=120 ) plt.hist( x, bins=25 , range=(12 , 18 ), color='royalblue' , orientation='horizontal' , edgecolor='k' , #bins边界上色 label=r'$\mu = 15, \sigma = 2) plt.legend()
4.6 多组直方图N = 1000 mu1 = 5 mu2 = 10 mu3 = 15 sigma1 = 5 sigma2 = 3 sigma3 = 2 x1 = np.random.randn(N) * sigma1 + mu1 x2 = np.random.randn(N) * sigma2 + mu2 x3 = np.random.randn(N) * sigma3 + mu3 plt.figure(dpi=120 ) plt.hist( x1, #变量1 bins=30 , color='royalblue' , label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1)) plt.hist( x2, #变量2 bins=30 , color='tomato' , label=r'$\mu = $ ' + str(mu2) + ', $\sigma = $ ' + str(sigma2)) plt.hist( x3, #变量3 bins=30 , color='gray' , label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3)) plt.legend()
4.7 直方图修改箱子透明度N = 1000 mu1 = 5 mu2 = 10 mu3 = 15 sigma1 = 5 sigma2 = 3 sigma3 = 2 x1 = np.random.randn(N) * sigma1 + mu1 x2 = np.random.randn(N) * sigma2 + mu2 x3 = np.random.randn(N) * sigma3 + mu3 plt.figure(dpi=120 ) plt.hist(x1, bins=30 , color='royalblue' , label=r'$\mu = $ ' + str(mu1) + ', $\sigma = $ ' + str(sigma1), alpha=.7 #透明度通过alpha设置 ) plt.hist(x2, bins=30 , color='tomato' , label=r'$\mu = $ ' + str(mu2) + ', $\sigma = $ ' + str(sigma2), alpha=.7 ) plt.hist(x3, bins=30 , color='gray' , label=r'$\mu = $ ' + str(mu3) + ', $\sigma = $ ' + str(sigma3), alpha=.7 ) plt.legend()
以上代码可以通过循环简化,
N = 1000 mu1 = 5 mu2 = 10 mu3 = 15 sigma1 = 5 sigma2 = 3 sigma3 = 2 x1 = np.random.randn(N) * sigma1 + mu1 x2 = np.random.randn(N) * sigma2 + mu2 x3 = np.random.randn(N) * sigma3 + mu3 mu = np.array([mu1, mu2, mu3]) sigma = np.array([sigma1, sigma2, sigma3]) x = np.array([x1, x2, x3]) colors = ['royalblue' , 'tomato' , 'gray' ] plt.figure(dpi=120 )#循环方式绘图 for i in range(len(x)): plt.hist(x[i], bins = 30 , color = colors[i], label = r'$\mu = $ ' + str(mu[i]) + ', $\sigma = $ ' + str(sigma[i]), alpha = .7 ) plt.legend()
4.8 更多组直方图通过循环,我们可以一图绘制更多直方图。
N_func = 10 N_data = 1000 np.random.seed(1000 ) mu = np.random.randint(low=-5 , high=5 , size=N_func) sigma = np.random.randint(low=1 , high=5 , size=N_func) x = []for i in range(len(mu)): xi = np.random.randn(N_data) * sigma[i] + mu[i] x.append(xi) colors = [ '#00429d' , '#7f40a2' , '#a653a1' , '#c76a9f' , '#e4849c' , '#d0e848' , '#b6cf54' , '#a9b356' , '#b2914b' , '#ff0001' ] plt.figure(dpi=120 )for i in range(len(mu)): plt.hist(x[i], bins=30 , color=colors[i], label=r'$\mu = $ ' + str(mu[i]) + ', $\sigma = $ ' + str(sigma[i]), alpha=.7 ) plt.legend(bbox_to_anchor=(1.33 , 1.03 ))
4.9 2D直方图N = 1 _000 np.random.seed(100 ) x = np.random.randn(N) y = np.random.randn(N) plt.hist2d(x, y) #2D直方图需要传入两个变量
4.10 2D直方图修改bins数N = 1 _000 np.random.seed(100 ) x = np.random.randn(N) y = np.random.randn(N) plt.hist2d(x, y, bins=(25 , 25 )) #2D直方图修改bins也需要传入两个变量
4.11 2D直方图定义colormapfrom matplotlib import cmfrom matplotlib.colors import ListedColormap, LinearSegmentedColormap top = cm.get_cmap('Oranges_r' , 128 ) bottom = cm.get_cmap('Blues' , 128 ) newcolors = np.vstack((top(np.linspace(0 , 1 , 128 )), bottom(np.linspace(0 , 1 , 128 )))) orange_blue = ListedColormap(newcolors, name='OrangeBlue' ) #自定义colormap N = 10 _000 np.random.seed(100 ) x = np.random.randn(N) y = np.random.randn(N) plt.figure(dpi=120 ) plt.hist2d( x, y, bins=(75 , 75 ), cmap=orange_blue #传入colormap ) cb = plt.colorbar() cb.set_label('counts each bin' , labelpad=10 )
4.12 2D直方图显示范围内变量N = 10 _000 np.random.seed(100 ) x = np.random.randn(N) y = np.random.randn(N) plt.figure(dpi=120 ) plt.hist2d(x, y, bins=(75 , 75 ), cmap='jet' , cmin=5 , cmax=25 #定义 ) cb = plt.colorbar() cb.set_label('counts each bin' , labelpad=10 )
4.13 边界直方图N = 10 _000 np.random.seed(100 ) x = np.random.randn(N) y = np.random.randn(N) rows = 5 columns = 5 grid = plt.GridSpec(rows, columns, wspace=.4 , hspace=.4 ) plt.figure(dpi=120 ) plt.subplot(grid[0 , 0 :-1 ]) plt.hist(x, bins=40 , color='royalblue' , alpha=.6 ) plt.annotate('Normal 1' , xy=(2 , 500 ), va='center' , ha='left' ) plt.subplot(grid[1 :rows + 1 , 0 :-1 ]) plt.hist2d(x, y, cmap='Blues' , bins=(30 , 40 )) plt.axis('equal' ) plt.subplot(grid[1 :rows + 1 , -1 ]) plt.hist(y, bins=40 , orientation='horizontal' , color='royalblue' , alpha=.6 ) plt.annotate('Normal 2' , xy=(500 , 2 ), va='bottom' , ha='center' , rotation=-90 )