Matplotlib.pyplot 常用方法(一)

来源:互联网 发布:sql 截断二进制数据 编辑:程序博客网 时间:2024/06/14 00:35

简介

matplotlib是python上的一个2D绘图库,它可以在夸平台上边出很多高质量的图像。综旨就是让简单的事变得更简单,让复杂的事变得可能。我们可以用matplotlib生成 绘图、直方图、功率谱、柱状图、误差图、散点图等 。

matplotlib.pyplot:提供一个类似matlab的绘图框架。

pylab将pyplot与numpy合并为一个命名空间。这对于交互式工作很方便,但是对于编程来说,建议将名称空间分开,例如 :

# 画 y = sin x 图像import numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 5, 0.1);y = np.sin(x)plt.plot(x, y)plt.show()

matplotlib实际上为面向对象的绘图库,它所绘制的每个元素都有一个对象与之对应的。例如上述例子中执行完 plt.plot(x,y) 之后得到:[matplotlib.lines.Line2D object at 0x01867D70]

好啦,现在开始学习:

配置属性:

因为是面向对象的绘图库,我们可以为每个对象配置它们的属性,应该说有三个方法,一个是通过对象的方法set_属性名()函数,二是通过对象的set()函数,三是通过pylot模块提供的setp()函数:

plt.figure()line = plt.plot(range(5))[0]                # plot函数返回的是一个列表,因为可以同时画多条线的哦;line.set_color('r')line.set_linewidth(2.0)plt.show()#————————————  或者  ————————————plt.figure()line = plt.plot(range(5))[0]    # plot函数返回的是一个列表,因为可以同时画多条线的哦; line.set(color = 'g',linewidth = 2.0)plt.show() #————————————  或者 ————————————plt.figure()lines = plt.plot(range(5),range(5),range(5),range(8,13))    # plot函数返回一个列表;plt.setp(lines, color = 'g',linewidth = 2.0)                # setp函数可以对多条线进行设置的;plt.show()

这里写图片描述
如果想查看呢,怎么办呢?同样两个方法,一个是通过对象的方法get_属性名()函数,一个是通过pylot模块提供的getp()函数。

getp()有两个调用方法,一个是只有要的查看的对象一个参数,一个是要查看的对象现属性两个参数;如:

# getp(obj, property=None)plt.getp(line)plt.getp(line, 'color')

Artist 对象

matplotlib API包含有三层:

  • backend_bases.FigureCanvas : 图表的绘制领域
  • backend_bases.Renderer : 知道如何在FigureCanvas上如何绘图
  • artist.Artist : 知道如何使用Renderer在FigureCanvas上绘图

FigureCanvas和Renderer需要处理底层的绘图操作,例如使用wxPython在界面上绘图,或者使用PostScript绘制PDF。Artist则处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和Artist打交道,而不需要关心底层的绘制细节。

Artists分为简单类型容器类型两种。简单类型的Artists为标准的绘图元件,例如Line2D、 Rectangle、 Text、AxesImage 等等。而容器类型则可以包含许多简单类型的Artists,使它们组织成一个整体,例如Axis、 Axes、Figure等。

直接使用Artists创建图表的标准流程如下:

  • 创建Figure对象
  • 用Figure对象创建一个或者多个Axes或者Subplot对象
  • 调用Axies等对象的方法创建各种简单类型的Artists

Artist 对象

对于上面的很多很多对象,其实都是Artist对象,Artist对象共分为简单类型和容器类型两种哦。
举一个建立简单Artist对象的过程哈,直接上代码:

import matplotlib.pyplot as pltimport numpy as npfig = plt.figure(1)        # 创建了一个figure对象;# figure对象的add_axes()可以在其中创建一个axes对象,# add_axes()的参数为一个形如[left, bottom, width, height]的列表,取值范围在0与1之间;# 我们把它放在了figure图形的上半部分,对应参数分别为:left, bottom, width, height;ax = fig.add_axes([0.1, 0.5, 0.8, 0.5]) ax.set_xlabel('time')           # 用axes对象的set_xlabel函数来设置它的xlabelline =ax.plot(range(5))[0]      # 用axes对象的plot()进行绘图,它返回一个Line2D的对象;line.set_color('r')             # 再调用Line2D的对象的set_color函数设置color的属性;plt.show()

输出 为:

这里写图片描述

figure 容器

在构成图表的各种Artist对象中,最上层的Artist对象是Figure。我们可以调用add_subplot()与add_axes()方法向图表中添加子图,它们分加到figure的axes的属性列表中。add_subplot()与add_axes()返回新创建的axes对象,分别为axesSuubplot与axes, axesSuubplot为 axes的派生类。另外,可以通过delaxes()方法来删除哦;

figure对象可以有自己的简单的artist对象。

下面列出Figure对象中包含的其他Artist对象的属性:

  • axes:Axes对象列表;
  • patch:作为背景的Rectangle对象;
  • images:FigureImage对象列表,用于显示图像;
  • legends:Legend 对象列表,用于显示图示;
  • lines:Line2D对象列表;
  • patches:Patch对象列表;
  • texts:Text 对象列表,用于显示文字;
# 使用figure对象绘制直线from matplotlib.lines import Line2Dimport matplotlib.pyplot as pltfig = plt.figure()line1 = Line2D([0,1],[0,1], transform=fig.transFigure, figure=fig, color="r")line2 = Line2D([0,1],[1,0], transform=fig.transFigure, figure=fig, color="b")fig.lines.extend([line1, line2])fig.show()

运行结果:
这里写图片描述

axes 容器

它是整个matplotlib的核心,它包含了组成图表的众多的artist对象。并且有很多方法。我们常用的Line2D啦,Xaxis,YAxis等都是它的属性哦;可以通过这个对象的属性来设置坐标轴的label啦,范围啦等之类的。干脆直接用plt.getp()查看它的属性,然后通过set_属性名()函数来设置就好啦。

axis 容器

axis容器包括了坐标轴上的刻度线、刻度标签等、坐标网络等内容。

对于坐标轴上的刻度相关的知识,它是这么分的:首先是major_ticks()和minor_ticks(), 然后呢,每个刻度又包括刻度线(ticklines)、刻度标签(ticklabels)、刻度位置(ticklocs)。本来呢,axis应该刻度,然后呢,刻度再包含那三个,但是呢,为了方便,axis就都包含了。其实也是有点交叉吧。上面的axes也会交叉包含它所包含对象的对象的。

看个例子:

from matplotlib.lines import Line2Dimport matplotlib.pyplot as plt# 通过axis来更改坐标轴plt.plot([1,2,3],[4,5,6])# gca()获取当前的axes绘图区域,调用gcf()来获得当前的figureaxis = plt.gca().xaxis        axis.get_ticklocs()                 # 得到刻度位置;axis.get_ticklabels()               # 得到刻度标签;axis.get_ticklines()                # 得到刻度线;axis.get_ticklines(minor = True)    # 得到次刻度线; 举个例子:就像我们的尺子上的厘米的为主刻度线,毫米的为次刻度线;for label in axis.get_ticklabels():      label.set_color('red')          # 设置每个刻度标签的颜色;    label.set_rotation(45)          # 旋转45度;    label.set_fontsize(16)          # 设置字体大小;for line in axis.get_ticklines():    line.set_color('green')              line.set_markersize(15)         # 设置刻度线的长短;    line.set_markeredgewidth(3)     # 设置线的粗细plt.show()

运行结果:
这里写图片描述

pyplot函数提供了两个绘制文字的函数:text()和figtext()。它们分别调用了当前的Axes对象与当前的Figure对象的text()方法进行绘制文字。text()默认在数字坐标系(就是axes在的坐标系,用坐标轴的数字来表示坐标)中画, figtext()默认在图表坐标系(就是figure在图表中啦,坐标范围从0 到 1 )中画,我们可能通过trransform参数进行坐标系的转换。反正吧,matplotlib中一共有四种坐标系,并且可以转换的哦,提一下哈。

简单的调用:

plt.text(1, 1, ‘hello,world’, color = ‘bule’) #还可以写更多参数的;
plt.figtexe(0.1, 0.8 ,”i am in figure’, color = ‘green’)

上面说了一大堆了,现在说几个常用的画图函数吧:

常用函数

plot()

可以画出很简单线图,基本用法:

plot(x, y)             # 画出横轴为x与纵轴为y的图,使用默认的线形与颜色;plot(x, y, 'bo')    # 用蓝色,且点的标记用小圆,下面会解释哦plot(y)             # 纵轴用y ,横轴用y的每个元素的坐标,即0,1,2……plot(y, 'r+')       # 如果其中x或y 为2D的,则会用它的相应的每列来表示哦,是每列哦,是每列哦,是每列哦,(重要的事情说三遍)plot(x1, y1, 'g^', x2, y2, 'g-') # 看到了吗,我们可以使用多对的x, y, format 对当作变量的哦,把它们画一个图里;

对于参数中,常用的format:线的颜色、线的形状、点的标记形状,我们用这三个的时候经常用缩写,它们之间的顺序怎么都可以哦,

如它俩一个意思:’r+–’、’+–r’。如果我们不想缩写的话,可以分别写成如: color=’green’, linestyle=’dashed’, marker=’o’。

线的形状:

‘-’ solid line style
‘–’ dashed line style
‘-.’ dash-dot line style
‘:’ dotted line style

点的标记:

‘.’ point marker
‘,’ pixel marker
‘o’ circle marker
‘v’ triangle_down marker
‘^’ triangle_up marker
‘<’ triangle_left marker
‘>’ triangle_right marker
‘1’ tri_down marker
‘2’ tri_up marker
‘3’ tri_left marker
‘4’ tri_right marker
‘s’ square marker
‘p’ pentagon marker
‘*’ star marker
‘h’ hexagon1 marker
‘H’ hexagon2 marker
‘+’ plus marker
‘x’ x marker
‘D’ diamond marker
‘d’ thin_diamond marker
‘|’ vline marker
‘_’ hline marker

线的颜色:

‘b’ blue
‘g’ green
‘r’ red
‘c’ cyan
‘m’ magenta
‘y’ yellow
‘k’ black
‘w’ white

常见线的属性有:color,labor,linewidth,linestyle,maker,等,具体要看全的话,见:lines–matplotlib。

看一个例子:

# 绘图并作标记import matplotlib.pyplot as pltimport numpy as np  plt.figure(1)                   # 调用figure函数创建figure(1)对象,可以省略,这样那plot时,它就自动建一个啦;t = np.arange(0.0, 2.0, 0.1)s = np.sin(2*np.pi*t)plt.plot(t, s, 'r--o', label = 'sinx')plt.legend()                    # 显示右上角的那个label,即上面的label = 'sinx'plt.xlabel('time (s)')          # 设置x轴的label,pyplot模块提供了很直接的方法,内部也是调用的上面当然讲述的面向对象的方式来设置;plt.ylabel('voltage (mV)')      # 设置y轴的label;#plt.xlim(-1,3)                 # 可以自己设置x轴的坐标的范围哦;#plt.ylim(-1.5,1.5)             plt.title('About as simple as it gets, folks')  plt.grid(True)                  # 显示网格;plt.show()   

运行结果:这里写图片描述

subplot()

利用subplot()函数可以返回一个axes的对象哦,函数为:subplot(numRows, numCols, plotnum),当这三个参数都小于10时,我们可以把它们写一起,如下所示:

# 填充彩色子图import matplotlib.pyplot as pltimport numpy as np for i, color in enumerate('rgbyck'):        plt.subplot(321+i, axis_bgcolor = color)plt.show()

这里写图片描述

利用subplot_adjust()函数可以对画的多个子图进行调整,优化间隔,它一共有left、right, bottom, top, wspace, hspase 六个参数,取 值从0至1。

"""Simple demo with multiple subplots."""import numpy as npimport matplotlib.pyplot as pltx1 = np.linspace(0.0, 5.0)   #生成一个一维的array,linspace(起始点,结束点,点数(默认为50))x2 = np.linspace(0.0, 2.0)y1 = np.cos(2 * np.pi * x1) * np.exp(-x1)y2 = np.cos(2 * np.pi * x2)plt.subplot(2, 2, 1)      #表示在subplot为2*1的样式,并在第一个子图上画出;plt.plot(x1, y1, 'yo-')plt.title('A tale of 2 subplots')plt.ylabel('Damped oscillation')plt.subplot(2, 2, 2)      #  我们在第二个子图上加个空图哈,去理解它的图的排序(即注意第二个子图的位置                                    #  为第一行第二列)是按行优先的,这个正好和matlab里相反哦;plt.title('It is a empty figure')plt.subplot(2, 2, 4)plt.plot(x2, y2, 'r.-')plt.xlabel('time (s)')plt.ylabel('Undamped')plt.show()

运行结果:
这里写图片描述

subplots()

plt.subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True, subplot_kw=None, **fig_kw)

作用:创建一个已有subplots的figures;
参数:

nrows : int ,指创建的sublots的行数,默认为1.
ncols : int ,指创建的sublots的列数,默认为1.
sharex : 为一个string或bool类型; 当为Ture时,所有的subpots将要共享x轴,如果它们是上下的关系的话,上面的图的刻度label就没有,只有下面那个图的.

    If a string must be one of "row", "col", "all", or "none".    "all" has the same effect as *True*, "none" has the same effect    as *False*.    If "row", each subplot row will share a X axis.    If "col", each subplot column will share a X axis and the x tick    labels on all but the last row will have visible set to *False*.  *sharey* : 同上  *squeeze* : bool  它是用来控制返回值的,根据返回的axis的结果决定要不要把没有的维度进行压缩一下.       当为Ture时,如果返回的axis只有一个,则表示成标量,如果有一行或一列,则表示为一维数组,如果多行多列,则表示为2D数组;       当为False时,不管多少个返回的axis,都以二维数组的方式返回;  *subplot_kw* : dict    Dict with keywords passed to the    :meth:`~matplotlib.figure.Figure.add_subplot` call used to    create each subplots.  *fig_kw* : dict    Dict with keywords passed to the :func:`figure` call.  Note that all    keywords not recognized above will be automatically included here.

返回值

有两个fig和 axt(它是元组的方式哦)

*fig* is the :class:matplotlib.figure.Figure object
*ax * can be either a single axis object or an array of axis objects if more than one subplot was created. The dimensions of the resulting array can be controlled with the squeeze keyword, see above.

# subplots() 返回值import matplotlib.pyplot as pltimport numpy as np  x = range(0,30,1)y = np.sin(x)# 接收返回的两个对象f,(ax1, ax2) = plt.subplots(1, 2, sharey=True)# 两个对象分别画图ax1.plot(x, y)ax1.set_title('Sharing Y axis')ax2.scatter(x, y)plt.show()figure_1

这里写图片描述

twinx()或twiny()

twinx():在同一图画中,共享x轴,但是拥有各自不同的y轴

create a twin of Axes for generating a plot with a sharex
x-axis but independent y axis. The y-axis of self will have
ticks on left and the returned axes will have ticks on the
right.

twiny():和上面一样,不同之处在于,它共享y轴。

# twinx() 共享x轴实例import matplotlib.pyplot as pltimport numpy as npfig = plt.figure(1)ax1 =plt.subplot(111)ax2 = ax1.twinx()ax1.plot(np.arange(1,5),'g--')ax1.set_ylabel('ax1',color = 'r')ax2.plot(np.arange(7,10),'b-')ax2.set_ylabel('ax2',color = 'b')plt.show()  

运行结果:
这里写图片描述



参考文章:
matplotlib.pyplot 官方文档
博客园——matplotlib 常用知识
博客园——matplotlib 绘图入门
matplotlib-绘制精美的图表(Figure容器,Artist对象,Axes容器)
博客园——Matplotlib 详解图像各个部分