python matplotlib各种绘图类型完整总结 | 您所在的位置:网站首页 › plot函数python画什么图 › python matplotlib各种绘图类型完整总结 |
文章目录
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()
调用形式一般为: 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:线条颜色![]() ![]() ![]() 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()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()坐标轴和上面的记号连在一起就形成了脊柱(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()在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()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。![]() ![]() 函数用于在图形上给数据点添加文本注解,而且支持带箭头的划线工具,方便我们在合适的位置添加描述信息。具体的内容可以参考Matplotlib中的annotate用法 参数: s: 注释文本中的内容color: 注释文本的颜色xy: 被注释的坐标点,二维元组形式(x, y)xytext: 注释文本的坐标点,也是二维元组(x, y)形式xycoords: 被注释的坐标系属性,允许输入的值如下图![]() ![]() ![]() ![]() ![]() 图像的属性包括以下几个: 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)灰度图和热力图的区别其实在于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()以下为自定义的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()箱线图是一种用作显示一组数据分散情况的统计图 箱线图有五个参数,分别为: 下边缘(Q1),表示最小值;下四分位数(Q2),又称“第一四分位数”,等于该样本中所有数值由小到大排列后第25%的数字;中位数(Q3),又称“第二四分位数”等于该样本中所有数值由小到大排列后第50%的数字;上四分位数(Q4),又称“第三四分位数”等于该样本中所有数值由小到大排列后第75%的数字;上边缘(Q5),表述最大值。箱线图各参数和正态分布之间的对比如下图: 像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 实验室设备网 版权所有 |