python matplotlib各种绘图类型完整总结 您所在的位置:网站首页 plot函数python画什么图 python matplotlib各种绘图类型完整总结

python matplotlib各种绘图类型完整总结

2024-01-25 16:38| 来源: 网络整理| 查看: 265

文章目录 1. Matplotlib图像基础1.1 __基本绘图实例:sin、cos函数图__1.2 plot()函数详解1.3 __matplotlib中绘图的默认配置__1.4 __设置图的横纵坐标的上下界:__1.5 __设置横纵坐标上的记号__1.6 __调整图像的脊柱__1.7 添加图例1.8 给一些特殊点加注释1.9 子图 2. 函数间区域填充函数 fill_between()和fill()3. 散点图4. 直方图5. 条形图5.1 一个数据样本的条形图5.2 多个数据样本进行对比的直方图5.3 水平条形图5.4 绘制不同数据样本进行对比的水平条形图5.5 堆叠条形图 6. 等高线图7. 雷达图7.1 圆形雷达图7.2 多边形雷达图 8. 极坐标图9. 折线图10. 灰度图11. 热力图11.1 自定义colormap 12. 箱线图13. 饼图14. 学会使用```help()```函数

1. Matplotlib图像基础 1.1 基本绘图实例:sin、cos函数图 from pylab import * import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) show()

1.2 plot()函数详解

调用形式一般为:

plot([x], y, [fmt], data=None, **kwargs)

plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)

其中可选参数[fmt]是一个字符串,用于定义图的基本属性:颜色(color)、点型(marker)、线型(linestyle) 具体形式为:fmt = [color][marker][linestyle],注意这里的三个属性只能是每个属性的单个字母缩写,若属性用的是全名则不能用[fmt]参数来组合赋值

**kwargs参数:

x: x轴数据y: y轴数据linewidth: 线宽color:线条颜色 在这里插入图片描述marker: 标记风格 在这里插入图片描述linestyle: 线条样式 在这里插入图片描述markerfacecolor 标记颜色markersize 标记大小 from pylab import * import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c, 'b|-') plt.plot(x, s) show()

在这里插入图片描述

1.3 matplotlib中绘图的默认配置 from pylab import * import numpy as np import matplotlib.pylab as plt # 创建一个8*6点(point)的图,并设置分辨率为80 figure(figsize=(8, 6), dpi=80) # 创建一个新的1*1的子图,接下来的图样绘制在其中的第一块中 subplot(1, 1, 1) # 得到坐标点(x,y)坐标 X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) # 绘制余弦曲线,使用蓝色的、连续的、宽度为1的线条 plot(X, C, color='blue', linewidth=2.5, linestyle='-') # 绘制正弦曲线,使用绿色的、连续的、宽度为1的线条 plot(X, S, color='green', linewidth=2.0, linestyle='-') # 设置横轴的上下限 xlim(-4.0, 4.0) # 设置横轴记号 xticks(np.linspace(-4, 4, 9, endpoint=True), fontproperties='Times New Roman', size=20) # 设置纵轴记号 yticks(np.linspace(-1, 1, 5, endpoint=True)) #设置横纵坐标的名称以及对应字体格式 font = {'family' : 'Times New Roman', 'weight' : 'normal', 'size' : 20, } # 设置横轴标签 plt.xlabel('X axis', font) # 设置纵轴标签 plt.ylabel('Y axis', font) # 设置图像标题 plt.title('Demo Figure', font) # 以分辨率72来保存图片 savefig('demo.png', dpi=72) # 在屏幕上显示 show()

在这里插入图片描述

1.4 设置图的横纵坐标的上下界:

xlim(), ylim()

from pylab import * import numpy as np # 得到坐标点(x,y)坐标 X = np.linspace(-np.pi, np.pi, 256, endpoint=True) C, S = np.cos(X), np.sin(X) x_min, x_max = X.min(), X.max() c_min, c_max = C.min(), C.max() s_min, s_max = S.min(), C.max() y_min, y_max = min(c_min, s_min), max(c_max, s_max) # 设置横纵坐标上下界的偏移量,这样能够完整的显示图像且最美观 dx = (x_max - x_min) * 0.2 dy = (y_max - y_min) * 0.2 # 设置上下限 xlim(x_min - dx, x_max + dx) ylim(y_min - dy, y_max + dy) # 绘制余弦曲线,使用蓝色的、连续的、宽度为1的线条 plot(X, C, color='blue', linewidth=2.5, linestyle='-') # 绘制正弦曲线,使用绿色的、连续的、宽度为1的线条 plot(X, S, color='green', linewidth=2.0, linestyle='-') show()

在这里插入图片描述

1.5 设置横纵坐标上的记号

xticks(), yticks()

这两个函数的用处在于指明横纵轴需要显示的内容和显示内容的位置,

参数的值可以有两种情况:

当横纵坐标的值为普通的数字时:参数为一个list,list中的元素为数字,此时两个函数的参数只需要这一个list当横纵坐标的值为公式(使用的latex中的公式表示,如’ p i pi pi’)或其他和当前的坐标值不同的值时:参数为两个list,第一个list为普通数字对应的是纵坐标值,第二个list为第一个list中纵坐标位置对应要显示的值,可以是公式也可以是其他和当前纵坐标值不同的表示 from pylab import * import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) xticks([-np.pi, -np.pi/2, 0, np.pi/2, np.pi], [r'$-\pi$', r'$-\pi/2$', r'$0$', r'$+\pi/2$', r'$+\pi$']) yticks([-1, 0, +1], [r'$-1$', r'$0$', r'$+1$']) plt.plot(x, c) plt.plot(x, s) show()

在这里插入图片描述

1.6 调整图像的脊柱

坐标轴和上面的记号连在一起就形成了脊柱(Spines,一条线段上又一系列凸起,是不是很像脊柱),它记录了数据区域的范围,它们可以放在任意位置,不过默认是放在图的四边。

实际上每幅图都有四条脊柱(上下左右),为了将脊柱放在图的中间,我们必须将其中的两条(上和右)设置为无色,然后调整剩下的两条到合适的位置——数据空间的0点

from pylab import * import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) # 设置坐标轴gca(),获取坐标轴信息 ax = gca() ''' 使用ax.spines[]选定边框,使用set_color()将选定的边框的颜色设为 none ''' ax.spines['right'].set_color('none') ax.spines['top'].set_color('none') ''' 移动坐标轴,将bottom即x坐标轴移动到y=0的位置 ax.xaixs为x轴,set_ticks_position()用于从上下左右(top/bottom/left/right)四条脊柱中选择一个作为x轴 使用set_position()设置边框位置:y=0的位置。位置的所有属性包括:outward、axes、data ''' ax.xaxis.set_ticks_position('bottom') ax.spines['bottom'].set_position(('data', 0)) ''' 将left 即y坐标轴设置到x=0的位置 ''' ax.yaxis.set_ticks_position('left') # 选定y轴 ax.spines['left'].set_position(('data', 0)) plt.show()

在这里插入图片描述

1.7 添加图例

在plot()函数中增加一个参数label,再通过legend()函数显示图例

from pylab import * import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c, label='cosine') plt.plot(x, s, label='sine') legend(loc='upper left') show()

在这里插入图片描述

1.8 给一些特殊点加注释

scatter(x, y, s=None, c=None, marker=None, cmap=None, norm=None, vmin=None, vmax=None, alpha=None, linewidths=None, verts=None, edgecolors=None, hold=None, data=None, **kwargs)

函数用于在图像中绘制散点

参数:

x/y:都是向量形式,且维度相同,分别对应坐标点的横纵坐标scalar: 标记大小,以平方磅为单位的标记面积,可以有一下形式: 数值标量 : 以相同的大小绘制所有标记。行或列向量 : 使每个标记具有不同的大小。x、y 和 sz 中的相应元素确定每个标记的位置和面积。sz 的长度必须等于 x 和 y 的长度。[] : 使用 36 平方磅的默认面积。 color: 标记的颜色,有下列不同的赋值方式: RGB 三元数或颜色名称 - 使用相同的颜色绘制所有标记。由 RGB 三元数组成的三列矩阵 - 对每个标记使用不同的颜色。矩阵的每行为对应标记指定一种 RGB 三元数颜色。行数必须等于 x 和 y 的长度向量 - 对每个标记使用不同的颜色,并以线性方式将 c 中的值映射到当前颜色图中的颜色。c 的长度必须等于 x 和 y 的长度。要更改坐标区的颜色图,请使用 colormap 函数。如果散点图中有三个点,并且您希望这些颜色成为颜色图的索引,请以三元素列向量的形式指定 c。 在这里插入图片描述 marker: 标记样式 在这里插入图片描述edgecolors: 轮廓颜色,参数形式和color类似alpha: 透明度,值在[0, 1]范围内,1表示不透明,0表示透明linewidths: 线宽,表示标记边缘的宽度,默认是"face"cmap: 自定义色彩盘,实际上就是一个三列的矩阵,shape为 [ N , 3 ] [N, 3] [N,3],一个实例可以参考matplotlib使用自己想要的color map ```annotate(s, xy, *args, **kwargs)```

函数用于在图形上给数据点添加文本注解,而且支持带箭头的划线工具,方便我们在合适的位置添加描述信息。具体的内容可以参考Matplotlib中的annotate用法

参数:

s: 注释文本中的内容color: 注释文本的颜色xy: 被注释的坐标点,二维元组形式(x, y)xytext: 注释文本的坐标点,也是二维元组(x, y)形式xycoords: 被注释的坐标系属性,允许输入的值如下图 在这里插入图片描述textcoords: 注释文本的坐标系属性,默认与xycoords属性值相同,除了允许输入xycoords的属性值,还允许输入以下两种: 在这里插入图片描述arrowprops: 用于标注的箭头的样式,这个参数是一个dict类型的数据。如果该属性为空,则会在注释文本和被注释点之间画一个箭头。箭头的样式可以通过arrowstyle关键字来指定默认的可选类型,arrowstyle关键字包含的默认类型包括以下: 在这里插入图片描述 如果没有arrowstyle关键字,则箭头的样式可以由以下关键字指定(注意arrowstyle和以下关键字不能同时存在) 在这里插入图片描述 箭头、坐标点和注释文本之间的关系属性包括如下图。其中connectionstyle属性用于控制注释点和注释文本之间的连接线的属性,比如弧度,角度之类的信息,这里还不是太清楚。 在这里插入图片描述 from pylab import * import numpy as np import matplotlib.pyplot as plt x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) # 调整图像的脊柱 ax = gca() ax.spines['right'].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') # 选定y轴 ax.spines['left'].set_position(('data', 0)) # 在2*np.pi/3的位置给两条函数曲线加上一个注释 t = 2 * np.pi / 3 plt.plot([t, t], [0, np.cos(t)], color='blue', linewidth=2.5,linestyle='--') scatter([t, ], [np.cos(t), ], 50, color='blue') annotate(r'$\sin(\frac{2\pi}{3})=\frac{\sqrt{3}}{2}$', xy=(t, np.sin(t)), xycoords='data', xytext=(+10, +30), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) plot([t,t],[0,np.sin(t)], color ='red', linewidth=2.5, linestyle="--") scatter([t,],[np.sin(t),], 50, color ='red') annotate(r'$\cos(\frac{2\pi}{3})=-\frac{1}{2}$',color='green', xy=(t, np.cos(t)), xycoords='data', xytext=(-90, -50), textcoords='offset points', fontsize=16, arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2")) # arc, angle, armA, rad show()

在这里插入图片描述

1.9 子图

图像的属性包括以下几个: 在这里插入图片描述

from pylab import * ''' subplot()函数的参数中,除最后一维的其他维表示子图的大小,最后一维表示当前子图在图像中的位置,如下实例,在2*2的网格里,第四个子图为(2, 2, 4) 创建横跨多个位置的子图用gridspec实现 ''' """ 添加多个固定大小的子图: fig = plt.figure(figsize=(10, 10), dpi=80, facecolor='red') ax1 = fig.add_subplot(2, 2, 1) ax2 = fig.add_subplot(2, 2, 4) ax1.plot() ... ax2.plot() ... """ subplot(2,2,1) xticks([]), yticks([]) text(0.5,0.5, 'subplot(2,2,1)',ha='center',va='center',size=20,alpha=.5) subplot(2,2,2) xticks([]), yticks([]) text(0.5,0.5, 'subplot(2,2,2)',ha='center',va='center',size=20,alpha=.5) subplot(2,2,3) xticks([]), yticks([]) text(0.5,0.5, 'subplot(2,2,3)',ha='center',va='center',size=20,alpha=.5) subplot(2,2,4) xticks([]), yticks([]) text(0.5,0.5, 'subplot(2,2,4)',ha='center',va='center',size=20,alpha=.5) # savefig('../figures/subplot-grid.png', dpi=64) show()

在这里插入图片描述

from pylab import * import matplotlib.gridspec as gridspec # gridspec的用法,可以使图像横跨多个坐标 G = gridspec.GridSpec(3, 3) axes_1 = subplot(G[0, :]) xticks([]), yticks([]) text(0.5,0.5, 'Axes 1',ha='center',va='center',size=24,alpha=.5) axes_2 = subplot(G[1,:-1]) xticks([]), yticks([]) text(0.5,0.5, 'Axes 2',ha='center',va='center',size=24,alpha=.5) axes_3 = subplot(G[1:, -1]) # 确定了这个子图的位置之后,就可以直接在上面画图,直到创建了下个新的子图 x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) #xticks([]), yticks([]) #text(0.5,0.5, 'Axes 3',ha='center',va='center',size=24,alpha=.5) axes_4 = subplot(G[-1,0]) xticks([]), yticks([]) ''' text()函数用于在图像上的特定位置加上一些文本,用于注释 ''' text(0.5,0.5, 'Axes 4',ha='center',va='center',size=24,alpha=.5) axes_5 = subplot(G[-1,-2]) xticks([]), yticks([]) text(0.5,0.5, 'Axes 5',ha='center',va='center',size=24,alpha=.5) #plt.savefig('../figures/gridspec.png', dpi=64) show()

在这里插入图片描述

from pylab import * ''' 使用axes()函数来确定当前子图的位置和大小,参数为一个list[x, y, width, height], x,y为当前子图的左下角坐标位置,width为子图的宽度,height为子图的高度 ''' axes([0.1,0.1,0.8,0.8]) xticks([]), yticks([]) text(0.6,0.6, 'axes([0.1,0.1,.8,.8])',ha='center',va='center',size=20,alpha=.5) axes([0.2,0.2,.3,.3]) x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) # xticks([]), yticks([]) # text(0.5,0.5, 'axes([0.2,0.2,.3,.3])',ha='center',va='center',size=16,alpha=.5) # plt.savefig("../figures/axes.png",dpi=64) show()

在这里插入图片描述

from pylab import * axes([0.1,0.1,.5,.5]) xticks([]), yticks([]) text(0.1,0.1, 'axes([0.1,0.1,.5,.5])',ha='left',va='center',size=16,alpha=.5) axes([0.2,0.2,.5,.5]) xticks([]), yticks([]) text(0.1,0.1, 'axes([0.2,0.2,.5,.5])',ha='left',va='center',size=16,alpha=.5) axes([0.3,0.3,.5,.5]) x = np.linspace(-np.pi, np.pi, 256, endpoint=True) c, s = np.cos(x), np.sin(x) plt.plot(x, c) plt.plot(x, s) # xticks([]), yticks([]) # text(0.1,0.1, 'axes([0.3,0.3,.5,.5])',ha='left',va='center',size=16,alpha=.5) axes([0.4,0.4,.5,.5]) xticks([]), yticks([]) text(0.1,0.1, 'axes([0.4,0.4,.5,.5])',ha='left',va='center',size=16,alpha=.5) # plt.savefig("../figures/axes-2.png",dpi=64) show() 2. 函数间区域填充函数 fill_between()和fill()

plt.fill_between(x, y1, y2, where, color, alpha)

参数:

x: x轴坐标值,为一个listy1: 第一条曲线对应的函数值,为x对应的函数值listy2: 第二条曲线对应的函数值,为x对应的函数值listwhere: 条件表达式,用于判断某个区间内是否进行填充,如果判断为True,则进行填充,否则不填充color: 填充区域的颜色alpha: 填充区域的透明度,1表示不透明,0表示完全透明

一些实例可以参考基于matplotlib的数据可视化(图形填充函数fill和fill_between)

import numpy as np import matplotlib.pyplot as plt n = 256 X = np.linspace(-np.pi,np.pi,n,endpoint=True) Y = np.sin(2*X) plt.axes([0.025,0.025,0.95,0.95]) plt.plot (X, Y+1, color='blue', alpha=1.00) plt.fill_between(X, 1, Y+1, color='blue', alpha=.25) plt.plot (X, Y-1, color='blue', alpha=1.00) plt.fill_between(X, -1, Y-1, (Y-1) > -1, color='blue', alpha=.25) plt.fill_between(X, -1, Y-1, (Y-1) "编程能力":70,"沟通技能":60,"专业知识":75,"团体协作":65,"工具掌握":70} #创建第二个人的数据 # 分别提取两个人的信息和对应的标签 data1=np.array([i for i in p1.values()]).astype(int) #提取第一个人的信息 data2=np.array([i for i in p2.values()]).astype(int) #提取第二个人的信息 label=np.array([j for j in p1.keys()]) #提取标签 angle = np.linspace(0, 2*np.pi, len(data1), endpoint=False) #data里有几个数据,就把整圆360°分成几份 # 闭合的目的是在绘图时能够生成闭合的环 angles = np.concatenate((angle, [angle[0]])) #增加第一个angle到所有angle里,以实现闭合 data1 = np.concatenate((data1, [data1[0]])) #增加第一个人的第一个data到第一个人所有的data里,以实现闭合 data2 = np.concatenate((data2, [data2[0]])) #增加第二个人的第一个data到第二个人所有的data里,以实现闭合 fig = plt.figure() ax = fig.add_subplot(111, polar=True) # 设置坐标轴为极坐标 # 绘制两个数据样本的闭合环 ax.plot(angles, data1, 'bo-', linewidth=2, color='green', alpha=0.5) ax.fill(angles, data1, facecolor='red', alpha=0.2) ax.plot(angles, data2, 'bo-', linewidth=2, color='blue', alpha=0.5) # ax.fill(angles, data2, facecolor='steelblue', alpha=0.5) # 设置圆周每一维上显示的样本 ax.set_thetagrids(angles * 180/np.pi, label, fontproperties='SimHei', color='gray', fontsize=13) # 设置在半径方向上要显示的文本和显示文本的角度 ax.set_rgrids(np.arange(0, 81, 20),angle=45) ax.set_rlim(0, 100) ax.set_title('matplotlib 雷达图', va='bottom', fontproperties='SimHei', color='gold', fontsize=15) #help(ax.set_thetagrids)

在这里插入图片描述

7.2 多边形雷达图 import numpy as np import matplotlib.pyplot as plt def plot_radar(data): criterion = [1, 1, 1, 1, 1, 1] # 基准雷达图 angles = np.linspace(0, 2 * np.pi, 5, endpoint=False) angles = np.concatenate((angles, [angles[0]])) #print(criterion) #print(angles) fig = plt.figure(facecolor='#87CEEB') # 创建画板并填充颜色 ax = fig.add_subplot(111, polar=True,) # 设置坐标为极坐标 # 绘制三个五边形 floor = 0 ceil = 2 labels = np.array(['x1', 'x2', 'x3', 'x4', 'x5']) # 绘制五边形的循环 for i in np.arange(floor, ceil + 0.5 ,0.5): ax.plot(angles, [i] * (6), '-', lw= 0.5, color='black') for i in range(5): ax.plot([angles[i], angles[i]], [floor, ceil], '-',lw=0.5, color='black') # 绘制雷达图 ax.plot(angles, criterion, 'b-', lw=2, alpha=0.4) ax.fill(angles, criterion, facecolor='b', alpha=0.3) #填充 ax.plot(angles, data, 'b-', lw=2, alpha=0.35) ax.fill(angles, data, facecolor='b', alpha=0.25) ax.set_thetagrids(angles * 180 / np.pi, labels) ax.spines['polar'].set_visible(False)#不显示极坐标最外的圆形 ax.set_theta_zero_location('N')#设置极坐标的起点(即0度)在正上方向 ax.grid(False)# 不显示分隔线 ax.set_yticks([]) # 不显示坐标间隔 ax.set_title('xxxxxxxxxxxx', va='bottom', fontproperties='SimHei') ax.set_facecolor('#87ceeb') # 填充绘图区域的颜色 # 保存文png图片 plt.subplots_adjust(left=0.09, right=1, wspace=0.25, hspace=0.25, bottom=0.13, top=0.91) plt.savefig('a_1.png') plt.show() data = [0.8, 0.9, 1.2, 1.0, 1.5, 0.8] plot_radar(data)

在这里插入图片描述

8. 极坐标图 import matplotlib.pyplot as plt import numpy as np N=20 theta=np.linspace(0,2*np.pi,N,endpoint=False)#均分角度 radii=10*np.random.rand(N)#随机角度 width=np.pi/4*np.random.rand(N)#随机宽度 ax=plt.subplot(111,projection='polar')#极坐标图绘制 bars=ax.bar(theta,radii,width=width,bottom=0.0)#哪个角度画,长度,扇形角度,从距离圆心0的地方开始画 for r,bar in zip(radii,bars): bar.set_facecolor(plt.cm.viridis(r/10.0)) bar.set_alpha(0.5) #添加颜色 plt.title('polar') plt.show()

在这里插入图片描述

9. 折线图 import matplotlib.pyplot as plt x = [5, 10, 15, 20, 25, 30, 35, 40] y = [17, 24, 29, 36, 38, 47, 59, 80] plt.plot(x, y, 'rs-', markersize=10)

在这里插入图片描述

10. 灰度图

灰度图和热力图的区别其实在于colormap的不同,灰度图采用的灰度map,而热力图一般采用的是多个颜色组成的彩色的map。

import numpy as np import matplotlib.pyplot as plt def f(x,y): return (1-x/2+x**5+y**3)*np.exp(-x**2-y**2) n = 10 x = np.linspace(-3,3,3.5*n) y = np.linspace(-3,3,3.0*n) X,Y = np.meshgrid(x,y) Z = f(X,Y) plt.axes([0.025,0.025,0.95,0.95]) plt.imshow(Z, interpolation='bicubic', cmap='bone', origin='lower') plt.colorbar(shrink=0.92) plt.xticks([]), plt.yticks([]) # savefig('../figures/imshow_ex.png', dpi=48) plt.show()

在这里插入图片描述

11. 热力图 import matplotlib.pyplot as plt import matplotlib.colors as col import matplotlib.cm as cm import numpy as np points = np.arange(-5, 5, 0.01) # print(points) xs, ys = np.meshgrid(points, points) z = np.sqrt(xs**2 + ys**2) # print(z) # 自定义colormap start_color = 'red' end_color = 'blue' cmap_1 = col.LinearSegmentedColormap.from_list('cmap1', [start_color, end_color]) plt.imshow(z, cmap=cmap_1, alpha=0.3) plt.show()

在这里插入图片描述

11.1 自定义colormap

以下为自定义的colormap实例。

import matplotlib.pyplot as plt points = np.arange(-5, 5, 1) # print(points) xs, ys = np.meshgrid(points, points) z = np.sqrt(xs**2 + ys**2) # 列表中包含的颜色数目并不固定,可以选多个 color = ['red', 'green', 'blue'] cmap_1 = col.LinearSegmentedColormap.from_list('cmap1', [start_color, end_color]) plt.imshow(z, cmap=cmap_1, alpha=1) plt.colorbar(shrink=0.92) plt.show()

在这里插入图片描述

12. 箱线图

箱线图是一种用作显示一组数据分散情况的统计图 在这里插入图片描述

箱线图有五个参数,分别为:

下边缘(Q1),表示最小值;下四分位数(Q2),又称“第一四分位数”,等于该样本中所有数值由小到大排列后第25%的数字;中位数(Q3),又称“第二四分位数”等于该样本中所有数值由小到大排列后第50%的数字;上四分位数(Q4),又称“第三四分位数”等于该样本中所有数值由小到大排列后第75%的数字;上边缘(Q5),表述最大值。

箱线图各参数和正态分布之间的对比如下图: 在这里插入图片描述

import matplotlib.pyplot as plt import pandas as pd import seaborn as sns import numpy as np # 0、导入数据集 df = pd.read_excel('boxplot_data.xlsx', 'Sheet1') fig = plt.figure() ax = fig.add_subplot(111) ax.boxplot(df['Age']) plt.show()

在这里插入图片描述

13. 饼图 import matplotlib.pyplot as plt import matplotlib matplotlib.rcParams['font.sans-serif'] = ['SimHei'] matplotlib.rcParams['axes.unicode_minus'] = False label_list = ["第一部分", "第二部分", "第三部分"] # 各部分标签 size = [55, 35, 10] # 各部分大小 color = ["steelblue", "green", "blue"] # 各部分颜色 explode = [0.05, 0, 0] # 各部分突出值 """ 绘制饼图 explode:设置各部分突出 label:设置各部分标签, labeldistance:设置标签文本距圆心位置,1.1表示1.1倍半径 autopct:设置圆里面文本 shadow:设置是否有阴影 startangle:起始角度,默认从0开始逆时针转 pctdistance:设置圆内文本距圆心距离 返回值 l_text:圆内部文本,matplotlib.text.Text object p_text:圆外部文本 """ patches, l_text, p_text = plt.pie(size, explode=explode, colors=color, labels=label_list, labeldistance=1.1, autopct="%1.1f%%", shadow=True, startangle=90, pctdistance=0.6) plt.axis("equal") # 设置横轴和纵轴大小相等,这样饼才是圆的 plt.legend() plt.show()

在这里插入图片描述

14. 学会使用help()函数

像matplotlib这样的包在python中是非常多的,里面涉及大量的函数接口及其参数定义,想同时都记住是不可能也没有必要的,网上讲解各种函数的参数含义和使用的博客之类的资源很多,但大部分都不全,所以最靠谱的全面学习这些函数接口的方法应该是通过使用官方提供的help()函数,当然官方文档是英文的,会对英语有一定要求,大家可以结合者官方文档和网上的博客来学习。下面举一个简单的例子,来说明一下help()函数的用法。

import matplotlib.pyplot as plt help(plt.figure) Help on function figure in module matplotlib.pyplot: figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True, FigureClass=, clear=False, **kwargs) Create a new figure. Parameters ---------- num : integer or string, optional, default: None If not provided, a new figure will be created, and the figure number will be incremented. The figure objects holds this number in a `number` attribute. If num is provided, and a figure with this id already exists, make it active, and returns a reference to it. If this figure does not exists, create it and returns it. If num is a string, the window title will be set to this figure's `num`. figsize : (float, float), optional, default: None width, height in inches. If not provided, defaults to :rc:`figure.figsize` = ``[6.4, 4.8]``. dpi : integer, optional, default: None resolution of the figure. If not provided, defaults to :rc:`figure.dpi` = ``100``. facecolor : color spec the background color. If not provided, defaults to :rc:`figure.facecolor` = ``'w'``. edgecolor : color spec the border color. If not provided, defaults to :rc:`figure.edgecolor` = ``'w'``. frameon : bool, optional, default: True If False, suppress drawing the figure frame. FigureClass : subclass of `~matplotlib.figure.Figure` Optionally use a custom `.Figure` instance. clear : bool, optional, default: False If True and the figure already exists, then it is cleared. Returns ------- figure : `~matplotlib.figure.Figure` The `.Figure` instance returned will also be passed to new_figure_manager in the backends, which allows to hook custom `.Figure` classes into the pyplot interface. Additional kwargs will be passed to the `.Figure` init function. Notes ----- If you are creating many figures, make sure you explicitly call :func:`.pyplot.close` on the figures you are not using, because this will enable pyplot to properly clean up the memory. `~matplotlib.rcParams` defines the default values, which can be modified in the matplotlibrc file.


【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有