matplotlib绘图函数简介

您所在的位置:网站首页 matplotlib函数绘图 matplotlib绘图函数简介

matplotlib绘图函数简介

#matplotlib绘图函数简介| 来源: 网络整理| 查看: 265

本文主要介绍使用matplotlib绘制一些常用的图表:

对数坐标图极坐标图柱状图散列图图像等值线图四边形网格三角网格箭头图三维绘图 首先对matplotlib的pyplot模块进行介绍:

首先看一个例子:

%matplotlib inline import numpy as np from matplotlib import pyplot as plt #%fig=使用pyplot模块快速将数据绘制成曲线图 import matplotlib.pyplot as plt #❶ x = np.linspace(0, 10, 1000) y = np.sin(x) z = np.cos(x**2) plt.figure(figsize=(8,4)) #❷ plt.plot(x,y,label="$sin(x)$",color="red",linewidth=2) #❸ plt.plot(x,z,"b--",label="$cos(x^2)$") #❹ plt.xlabel("Time(s)") #❺ plt.ylabel("Volt") plt.title("PyPlot First Example") plt.ylim(-1.2,1.2) plt.legend() plt.show() #❻

①首先载入matplotlib的绘图模块pyplot;

②调用figure()创建一个Figure(图表)对象;

③调用plot()在当前的Figure对象中绘图;

④通过第三个参数“b--”指定曲线的颜色和线型,“b”表示蓝色,“--”表示线型为虚线;

⑤xlabel,ylabel设置X、Y轴的标题文字,title设置子图的标题,xlim、ylim分别设置X,Y轴的显示范围,legend显示图示,即图中表示每条曲线的标签和样式矩形区域;

⑥plt.show()显示绘图窗口

 

绘制多子图

subplot(numRows,numCols,plotNum)

图表的整个绘图区被等分为numRows行和numCols列,然后按照从左到右、从上到下的顺序对每个区域编号。plotNum参数指定所创建Axes对象的区域。如果numRows,numCols,plotNum三个参数都小于10,则可以把他们缩写成一个整数,例如subplot(323)=subplot(3,2,3).

例子:

#%fig[1x2]=在Figure对象中创建多个子图 for idx, color in enumerate("rgbyck"): plt.subplot(321+idx)

如果希望某个子图占据整行或整列,可以如下调用subplot():

plt.subplot(221) # 第一行的左图 plt.subplot(222) # 第一行的右图 plt.subplot(212) # 第二整行; plt.show()

如果需要同时绘制多幅图表,可以给figure()传递一个整数参数来指定Figure对象的序号,如果序号指定的Figure对象已经存在,将不创建新的对象,而是让它成为当前的Figure对象。例子:

#%fig[1x2]=同时在多幅图表、多个子图中进行绘图 plt.figure(1) # 创建图表1 plt.figure(2) # 创建图表2 ax1 = plt.subplot(121) # 在图表2中创建子图1 ax2 = plt.subplot(122) # 在图表2中创建子图2 x = np.linspace(0, 3, 100) for i in range(5): plt.figure(1) #❶ 选择图表1 plt.plot(x, np.exp(i*x/3)) plt.sca(ax1) #❷ 选择图表2的子图1 plt.plot(x, np.sin(i*x)) plt.sca(ax2) # 选择图表2的子图2 plt.plot(x, np.cos(i*x)) plt.show()

首先通过figure()创建了两个图表,序号分别为1和2,然后在图表2中创建了左右并排的两个子图,并用变量ax1和ax2保存。

①首先调用figure(1)让图表1成为当前图表,并在其中绘图;

②调用sca(ax1)和sca(ax2)分别让子ax1和ax2成为当前子图,并在其中绘图;

此外subplots()可以一次生成多个子图,并返回图表对象和保存子图对象的数组。例子:

#%nofig fig, axes = plt.subplots(2, 3) [a, b, c], [d, e, f] = axes print(axes.shape) print (b)

对数坐标图

绘制对数坐标图的函数有三个:

semilogx():绘制X轴为对数坐标

semilogy():绘制Y轴为对数坐标

loglog():以两个轴为对数坐标

例子:

#%fig=低通滤波器的频率响应:算术坐标(左上)、X轴对数坐标(右上)、Y轴对数坐标(左下)、双对数坐标(右上) w = np.linspace(0.1, 1000, 1000) p = np.abs(1/(1+0.1j*w)) # 计算低通滤波器的频率响应 fig, axes = plt.subplots(2, 2) functions = ("plot", "semilogx", "semilogy", "loglog") for ax, fname in zip(axes.ravel(), functions): func = getattr(ax, fname) func(w, p, linewidth=2) ax.set_ylim(0, 1.5)

      2.极坐标图

极坐标系和笛卡尔坐标系是完全不同的坐标系,极坐标系中的点由一个夹角和一段相对中心点的距离表示。

例子:

#%fig=极坐标中的圆、螺旋线和玫瑰线 theta = np.arange(0, 2*np.pi, 0.02) plt.subplot(121, polar=True) #❶创建子图 plt.plot(theta, 1.6*np.ones_like(theta), linewidth=2) #❷调用plot()在极坐标子图中绘图 plt.plot(3*theta, theta/3, "--", linewidth=2) plt.subplot(122, polar=True) plt.plot(theta, 1.4*np.cos(5*theta), "--", linewidth=2) plt.plot(theta, 1.8*np.cos(4*theta), linewidth=2) plt.rgrids(np.arange(0.5, 2, 0.5), angle=45) #❸ plt.thetagrids([0, 45]) #❹;

③rgrids()设置同心圆栅格的半径大小和文字标注的角度,因此右图中的虚线圆圈有三个:半径分别为0.5,1.0和1.5.文字沿45°线排列。

④thetagrids()设置放射线栅格的角度,因此右图中只有两条放射线栅格线,分别为0°和45°。

     3.柱状图

柱状图使用每根柱子的长度表示值得大小,通常用来比较两组或多组值。

例子:

#%fig=中国男女人口的年龄分布图 from matplotlib.font_manager import FontProperties font_set = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=12) data = np.loadtxt("china_population.txt") width = (data[1,0] - data[0,0])*0.4 #❶ plt.figure(figsize=(8, 4)) plt.bar(data[:,0]-width, data[:,1]/1e7, width, color='r', label=u'male') #❷ plt.bar(data[:,0], data[:,2]/1e7, width, color='g', label=u'female') #❸ plt.xlim(-width, 100) plt.xlabel(u'年龄', fontproperties=font_set) plt.ylabel(u'人口(千万)', fontproperties=font_set) plt.legend();

china_population.txt 文本内容如下:

Age "Male Population" "Female Population" 0 40516152 34695655 5 41347074 34980960 10 48800919 42314154 15 57922621 52041688 20 60617499 56640842 25 51546942 48822129 30 49349671 47232809 35 62269539 59387454 40 61990087 59063706 45 46195684 44384976 50 43126682 40763133 55 38552648 37330255 60 26404372 25368901 65 19680421 19130240 70 15747177 16122226 75 10754214 11999674 80 5371220 6941742 85 1883174 3022617 90 358956 756105 95 39188 108857 100 1882 7338

①读入的数据第一列为年龄,作为柱状图的横坐标。以年龄段的0.4倍作为柱子的宽度。

②③调用bar()绘制男性人口分布的柱状图,第一个参数为每根柱子的左边缘的横坐标,为了让男性和女性的柱子以年龄可读为中心,让每根柱子左侧的横坐标为“年龄-柱子的宽度”;第二个参数为每根柱子的高度;第三个参数指定所有柱子的宽度。当第三个参数为序列时,可以为每根柱子给定宽度。

     4.散列图

通过scatter()绘制散列图

例子:

#%fig=可指定点的颜色和大小的散列 plt.figure(figsize=(8, 4)) x = np.random.random(100) y = np.random.random(100) plt.scatter(x, y, s=x*1000, c=y, marker=(5,3), alpha=0.8, lw=2, facecolors="none") plt.xlim(0, 1) plt.ylim(0, 1);

scatter()参数说明:

前两个参数是两个数组,分别指定每个点的X轴和Y轴的坐标;

s参数指定点的大小,其值和点的面积成正比,可以是单个数值或数组;

c参数指定每个点的颜色,也可以是数值或数组,这里使用一维数组为每个点制定了一个数值,当c参数是形状为(N,3)或(N,4)时,则直接表示每个点的RGB颜色;

marker参数设置点的形状,第一个元素便是多边形的边数,第二个参数便是多边形的样式,取值0(多边形),1(星形),2(放射形),3(活了边数显示为原型);

alpha参数设置点的透明度;

lw参数设置线宽;

facecolors为“none”表示散列点没有填充色。

5.图像

imread()和imshow()提供了简单的图像载入和显示功能。

imread()可以从图像文件读入数据,得到一个表示图像的Numpy数组。第一个参数是文件名或文件对象,format参数指定图像类型,如果省略择优文件的扩展名决定图像类型。对于灰度图像,它返回一个形状为(M,N)的数组;对于彩色图像,返回形状为(M,N,C)的数组,M为图像高度,N为图像的宽度,C表示图像的通道数,为3或4。

例子:

#%fig=用imread()和imshow()显示图像 img = plt.imread("lena.jpg") fig, axes = plt.subplots(2, 3, figsize=(11, 4)) fig.subplots_adjust(0, 0, 1, 1, 0.05, 0.05) axes = axes.ravel() axes[0].imshow(img) #❶ axes[1].imshow(img, origin="lower") #❷ axes[2].imshow(img / 255.0) #❹ axes[3].imshow(np.clip(img / 200.0, 0, 1)) #❺ axe_img = axes[4].imshow(img[:, :, 0]) #❻ plt.colorbar(axe_img, ax=axes[5]) axe_img = axes[5].imshow(img[:, :, 0], cmap="copper") #❼ plt.colorbar(axe_img, ax=axes[5]) for ax in axes: ax.set_axis_off()

①imshow()用来显示imread()所返回的数组。如果数组是表示多通道图像的三维数组,则每个像素的颜色由各个通道的值决定。

②origin参数为“lower”,所显示图表的原点在左下角,整个图像上下颠倒

④取值在0.0-1.0的浮点数组和原始图像完全相同

⑤使用clip()将超出范围的值限制在取值范围内,可以使整个图像变亮

⑥如果imshow()参数是二位数组,则使用颜色映射表决定每个像素的颜色,这里显示图像中的红色通道,它是一个二位数组,默认的图像映射将最小值映射为蓝色,将最大值映射为红色,可以使用colorbar()将颜色映射表在图表中显示出来。

⑦cmap参数可以修改显示图像时所采用的颜色映射表,使用“copper”的颜色映射表显示图像的红色通道

颜色映射表是一个ColorMap对象,matplotlib预定义了很多颜色映射表,可以通过以下语句查看:

import matplotlib.cm as cm cm.cmap_d.keys() dict_keys(['Blues', 'BrBG', 'BuGn', 'BuPu', 'CMRmap', 'GnBu', 'Greens', 'Greys', 'OrRd', 'Oranges', 'PRGn', 'PiYG', 'PuBu', 'PuBuGn', 'PuOr', 'PuRd', 'Purples', 'RdBu', 'RdGy', 'RdPu', 'RdYlBu', 'RdYlGn', 'Reds', 'Spectral', 'Wistia', 'YlGn', 'YlGnBu', 'YlOrBr', 'YlOrRd', 'afmhot', 'autumn', 'binary', 'bone', 'brg', 'bwr', 'cool', 'coolwarm', 'copper', 'cubehelix', 'flag', 'gist_earth', 'gist_gray', 'gist_heat', 'gist_ncar', 'gist_rainbow', 'gist_stern', 'gist_yarg', 'gnuplot', 'gnuplot2', 'gray', 'hot', 'hsv', 'jet', 'nipy_spectral', 'ocean', 'pink', 'prism', 'rainbow', 'seismic', 'spring', 'summer', 'terrain', 'winter', 'Accent', 'Dark2', 'Paired', 'Pastel1', 'Pastel2', 'Set1', 'Set2', 'Set3', 'tab10', 'tab20', 'tab20b', 'tab20c', 'Blues_r', 'BrBG_r', 'BuGn_r', 'BuPu_r', 'CMRmap_r', 'GnBu_r', 'Greens_r', 'Greys_r', 'OrRd_r', 'Oranges_r', 'PRGn_r', 'PiYG_r', 'PuBu_r', 'PuBuGn_r', 'PuOr_r', 'PuRd_r', 'Purples_r', 'RdBu_r', 'RdGy_r', 'RdPu_r', 'RdYlBu_r', 'RdYlGn_r', 'Reds_r', 'Spectral_r', 'Wistia_r', 'YlGn_r', 'YlGnBu_r', 'YlOrBr_r', 'YlOrRd_r', 'afmhot_r', 'autumn_r', 'binary_r', 'bone_r', 'brg_r', 'bwr_r', 'cool_r', 'coolwarm_r', 'copper_r', 'cubehelix_r', 'flag_r', 'gist_earth_r', 'gist_gray_r', 'gist_heat_r', 'gist_ncar_r', 'gist_rainbow_r', 'gist_stern_r', 'gist_yarg_r', 'gnuplot_r', 'gnuplot2_r', 'gray_r', 'hot_r', 'hsv_r', 'jet_r', 'nipy_spectral_r', 'ocean_r', 'pink_r', 'prism_r', 'rainbow_r', 'seismic_r', 'spring_r', 'summer_r', 'terrain_r', 'winter_r', 'Accent_r', 'Dark2_r', 'Paired_r', 'Pastel1_r', 'Pastel2_r', 'Set1_r', 'Set2_r', 'Set3_r', 'tab10_r', 'tab20_r', 'tab20b_r', 'tab20c_r', 'magma', 'magma_r', 'inferno', 'inferno_r', 'plasma', 'plasma_r', 'viridis', 'viridis_r', 'cividis', 'cividis_r'])

6.三维绘图

mpl_toolkits.mplot3d模块在matplotlib基础上提供了三维作图的功能。

例子:

#%fig=使用mplot3D绘制的三维曲面图 import mpl_toolkits.mplot3d #❶ x, y = np.mgrid[-2:2:20j, -2:2:20j] #❷ z = x * np.exp( - x**2 - y**2) fig = plt.figure(figsize=(8, 6)) ax = plt.subplot(111, projection='3d') #❸ ax.plot_surface(x, y, z, rstride=2, cstride=1, cmap = plt.cm.Blues_r) #❹ ax.set_xlabel("X") ax.set_ylabel("Y") ax.set_zlabel("Z");

①载入mplot3d模块;

②mgrid创建X-Y平面的网格并计算网格上每个点的高度z,和imshow()不同,数组的第0轴可以便是X和Y轴的任意一个;

③在当前图表中创建一个子图,通过projection参数指定子图的投影模式为“3d”

④调用plot_surface()绘制三维曲面图。其中x、y、z都是形状为(20,20)的二维数组,x和y构成了X-Y平面上的网格,而数组z则是网格上各点在曲面上的取值,通过cmap参数指定值和颜色之间的映射,即曲面上各点的高度值和颜色的对应关系;rstride和cstride分别是数组的第0轴和第1轴的下标间隔。

 

投影模式决定了点从数据坐标转换为屏幕坐标的方式,可以通过以下语句查看模式名称:

from matplotlib import projections projections.get_projection_names() ['3d', 'aitoff', 'hammer', 'lambert', 'mollweide', 'polar', 'rectilinear']

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3