matplotlib作图

来源:互联网 发布:36氪 知乎 编辑:程序博客网 时间:2024/05/01 21:35

转自;http://blog.csdn.net/pipisorry/article/details/37742423

matplotlib介绍

        matplotlib 是Python最著名的绘图库,它提供了一整套和matlab相似的命令API,十分适合交互式地进行制图。而且也可以方便地将它作为绘图控件,嵌入GUI应用程序中。它的文档相当完备,并且Gallery页面 中有上百幅缩略图,打开之后都有源程序。因此如果你需要绘制某种类型的图,只需要在这个页面中浏览/复制/粘贴一下,基本上都能搞定。
        在Linux下比较著名的数据图工具还有gnuplot,这个是免费的,Python有一个包可以调用gnuplot,但是语法比较不习惯,而且画图质量不高。而Matplotlib则比较强:Matlab的语法、python语言、latex的画图质量(还可以使用内嵌的latex引擎绘制的数学公式)。

    可以在Ipython中输入类似"plt.plot??"的命令查看pyplot模块的函数是如何对各种绘图对象进行包装的。

面向对象方式绘图

matplotlib实际上是一套面向对象的绘图库,它所绘制的图表中的每个绘图元素,例如线条Line2D、文字Text、刻度等在内存中都有一个对象与之对应。

为了方便快速绘图matplotlib通过pyplot模块提供了一套和MATLAB类似的绘图API,将众多绘图对象所构成的复杂结构隐藏在这套API内部。我们只需要调用pyplot模块所提供的函数就可以实现快速绘图以及设置图表的各种细节。pyplot模块虽然用法简单,但不适合在较大的应用程序中使用

获取当前图和轴线

为了将面向对象的绘图库包装成只使用函数的调用接口,pyplot模块的内部保存了当前图表以及当前子图等信息。当前的图表和子图可以使用plt.gcf()和plt.gca()获得,分别表示"Get Current Figure"和"Get Current Axes"。在pyplot模块中,许多函数都是对当前的Figure或Axes对象进行处理,比如说:    plt.plot()实际上会通过plt.gca()获得当前的Axes对象ax,然后再调用ax.plot()方法实现真正的绘图。

如,用下面的代码先获得axes对象再用ax来操作

ax = plt.gca()ax = plt.axes()

地如设置xy轴的tickers就要用ax.yaxis来操作

ax.yaxis.set_minor_locator(yminorLocator)

安装numpy和matplotlib

pip install numpy

pip install matplotlib

matplotlib安装出错

ImportError: libBLT.2.4.so.8.6: cannot open shared object file: No such file or directory, please install the python3-tk package

[import matplotlib.pyplot as plt fails with error about python-tk]

检测是否安装成功:

>>> import numpy
>>> numpy.__version__

>>> import matplotlib
>>> matplotlib.__version__

不同绘图语言比较

工科生说Matlab完爆其他
数学系的说Mathematica高贵冷艳
统计系的说R语言作图领域天下无敌 
计算机系的说Python低调奢华有内涵
[如何在论文中画出漂亮的插图]


matplotlib.pyplot模块 - 快速绘图

matplotlib的pyplot子库提供了和matlab类似的绘图API,方便用户快速绘制2D图表。

1.调用figure创建一个绘图对象,并且使它成为当前的绘图对象。(可选)

plt.figure(figsize=(8,4))
也可以不创建绘图对象直接调用接下来的plot函数直接绘图,matplotlib会为我们自动创建一个绘图对象!!
如果需要同时绘制多幅图表的话,可以是给figure传递一个整数参数指定图标的序号,如果所指定序号的绘图对象已经存在的话,将不创建新的对象,而只是让它成为当前绘图对象。
figsize参数:指定绘图对象的宽度和高度,单位为英寸;dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80。因此本例中所创建的图表窗口的宽度为8*80 = 640像素。
但是用show()出来的工具栏中的保存按钮保存下来的png图像的大小是800*400像素。这是因为保存图表用的函数savefig使用不同的DPI配置,savefig函数也有一个dpi参数,如果不设置的话,将使用matplotlib配置文件中的配置,此配置可以通过如下语句进行查看:>>>matplotlib.rcParams["savefig.dpi"]100

2.通过调用plot函数在当前的绘图对象中进行绘图

    plt.plot(years, price, 'b*')#,label="$cos(x^2)$")
    plt.plot(years, price, 'r')
Note:
1. 第一句将x,y数组传递给plot
2.通过第三个参数"b--"指定曲线的颜色和线型,这个参数称为格式化参数,它能够通过一些易记的符号快速指定曲线的样式。其中b表示蓝色,"--"表示线型为虚线。
3. 用关键字参数指定各种属性:label : 给所绘制的曲线一个名字,此名字在图示/图例(legend)中显示。只要在字符串前后添加"$"符号,matplotlib就会使用其内嵌的latex引擎绘制的数学公式。color : 指定曲线的颜色linewidth : 指定曲线的宽度
具体参见【附录 - matplotlib中的作图参数】

3.设置绘图对象的各个属性

    plt.xlabel("years(+2000)")   #设置X轴的文字
    plt.ylabel("housing average price(*2000 yuan)")
    plt.ylim(0, 15)    #设置Y轴的范围
    plt.title('line_regression & gradient decrease')    #设置图表的标题
    plt.legend()    #显示图示

设置xlabel和ylabel显示的大小

import matplotlibmatplotlib.rc('xtick', labelsize=18)matplotlib.rc('ytick', labelsize=18)

给一些特殊点做注释

我们希望在 2π/3的位置给两条函数曲线加上一个注释。首先,我们在对应的函数图像位置上画一个点;然后,向横轴引一条垂线,以虚线标记;最后,写上标签。

12345678910111213141516171819
...t = 2*np.pi/3plot([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}$',         xy=(t, np.cos(t)), xycoords='data',         xytext=(-90, -50), textcoords='offset points', fontsize=16,         arrowprops=dict(arrowstyle="->", connectionstyle="arc3,rad=.2"))...

点击图片下载相应 Python 代码

精益求精

坐标轴上的记号标签被曲线挡住了,作为强迫症患者(雾)这是不能忍的。我们可以把它们放大,然后添加一个白色的半透明底色。这样可以保证标签和曲线同时可见。

12345
...for label in ax.get_xticklabels() + ax.get_yticklabels():    label.set_fontsize(16)    label.set_bbox(dict(facecolor='white', edgecolor='None', alpha=0.65 ))...

点击图片下载相应 Python 代码

[Matplotlib 教程*]

plt.text(0.5,0.8,'subplot words',color='blue',ha='center',transform=ax.trans    Axes)  

plt.figtext(0.1,0.92,'figure words',color='green')  

plt.annotate('buttom',xy=(0,0),xytext=(0.2,0.2),arrowprops=dict(facecolor='blue', shrink=0.05))  


[matplotlib绘图,图标注释(2) ]

4.最后调用plt.show()显示出我们创建的所有绘图对象。

Matplotlib 里的常用类的包含关系为 Figure -> Axes -> (Line2D, Text, etc.)一个Figure对象可以包含多个子图(Axes),在matplotlib中用Axes对象表示一个绘图区域,可以理解为子图。

matplotlib绘图显示同时继续跑下面的代码

方式1:block=False参数或者plt.show(0)

from matplotlib.pyplot import plot, draw, showdef p():    plot([1, 2, 3])    show(block=False)p()print('continue computation')input()
但是在外部应该加一个input()输入enter结束图形显示,否则鼠标点击是关闭不了图形的。

方式2:draw()

from matplotlib.pyplot import plot, draw, showdef p():    plot([1, 2, 3])    draw()p()print('continue computation')# at the end call show to ensure window won't close.show()
唯一的缺点就是,show()函数放在了绘图函数外了。

方式3:使用多线程

from multiprocessing import Processfrom matplotlib import pyplot as pltdef p(args):    plt.plot([1, 2, 3])    plt.show()p = Process(target=p, args=([1, 2, 3],))p.start()print('continue computation')p.join()

唯一的缺点就是要写多线程的代码,但是至少plot模块都在一个函数中。

Note: target应为函数名而不应该是函数调用,否则还是会绘图阻止程序向下运行。

[Is there a way to detach matplotlib plots so that the computation can continue?]

清空plt绘制的内容

plt.cla()

plt.close(0)# 关闭图 0

plt.close('all') 关闭所有图

图形保存和输出设置

可以调用plt.savefig()将当前的Figure对象保存成图像文件,图像格式由图像文件的扩展名决定。下面的程序将当前的图表保存为“test.png”,并且通过dpi参数指定图像的分辨率为 120,因此输出图像的宽度为“8X120 = 960”个像素。
plt.savefig("test.png",dpi=120)
也可以通过show()出来的图形界面手动保存和设置
matplotlib中绘制完成图形之后通过show()展示出来,我们还可以通过图形界面中的工具栏对其进行设置和保存
matplotlib修改图片大小:图形界面下方工具栏可以设置图形上下左右的边距
如果想在跑程序外部查看图片,可以这样:

plt.savefig('/tmp/1.png')subprocess.run('xdg-open /tmp/1.png', shell=True)
有个问题就是绘制的图中横纵坐标下面的+3.156e1代表什么意思?也不是坐标值的单位,那是什么呢。。。

5. 绘制多子图
可以使用subplot()快速绘制包含多个子图的图表,它的调用形式如下:
subplot(numRows, numCols, plotNum)

matplotlib.pyplot.subplots(nrows=1ncols=1sharex=Falsesharey=Falsesqueeze=Truesubplot_kw=Nonegridspec_kw=None**fig_kw)

subplot将整个绘图区域等分为numRows行* numCols列个子区域,然后按照从左到右,从上到下的顺序对每个子区域进行编号,左上的子区域的编号为1。如果numRows,numCols和plotNum这三个数都小于10的话,可以把它们缩写为一个整数,例如subplot(323)和subplot(3,2,3)是相同的。subplot在plotNum指定的区域中创建一个轴对象。如果新创建的轴和之前创建的轴重叠的话,之前的轴将被删除。

通过axisbg参数给每个轴设置不同的背景颜色。

image

subplot()返回它所创建的Axes对象,我们可以将它用变量保存起来,然后用sca()交替让它们成为当前Axes对象,并调用plot()在其中绘图。

调节轴之间的间距和轴与边框之间的距离

当绘图对象中有多个轴的时候,可以通过工具栏中的Configure Subplots按钮,交互式地调节轴之间的间距和轴与边框之间的距离。

如果希望在程序中调节的话,可以调用subplots_adjust函数,它有left, right, bottom, top, wspace, hspace等几个关键字参数,这些参数的值都是0到1之间的小数,它们是以绘图区域的宽高为1进行正规化之后的坐标或者长度。

[matplotlib.pyplot.subplots_adjust]

[matplotlib.pyplot.subplots]

6.绘制多图表

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

[python] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. import numpy as np  
  2. import matplotlib.pyplot as plt   
  3.   
  4. plt.figure(1# 创建图表1  
  5. plt.figure(2# 创建图表2  
  6. ax1 = plt.subplot(211# 在图表2中创建子图1  
  7. ax2 = plt.subplot(212# 在图表2中创建子图2  
  8.    
  9. x = np.linspace(03100)  
  10. for i in xrange(5):  
  11.     plt.figure(1)  #选择图表1  
  12.     plt.plot(x, np.exp(i*x/3))  
  13.     plt.sca(ax1)   #选择图表2的子图1  
  14.     plt.plot(x, np.sin(i*x))  
  15.     plt.sca(ax2)  # 选择图表2的子图2  
  16.     plt.plot(x, np.cos(i*x))  
  17. plt.show()  
/tech/static/books/scipy/_images/matplotlib_multi_figure.png

7. 在图表中显示中文

matplotlib的缺省配置文件中所使用的字体无法正确显示中文。为了让图表能正确显示中文,可以有几种解决方案。

  1. 在程序中直接指定字体。
  2. 在程序开头修改配置字典rcParams。
  3. 修改配置文件。

比较简便的方式是,中文字符串用unicode格式,例如:u''测试中文显示'',代码文件编码使用utf-8 加上" # coding = utf-8  "一行。

[matplotlib输出图象的中文显示问题]

8. 面向对象画图

matplotlib API包含有三层,Artist层处理所有的高层结构,例如处理图表、文字和曲线等的绘制和布局。通常我们只和Artist打交道,而不需要关心底层的绘制细节。

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

  • 创建Figure对象
  • 用Figure对象创建一个或者多个Axes或者Subplot对象
  • 调用Axies等对象的方法创建各种简单类型的Artists
[python] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. import matplotlib.pyplot as plt  
  2. X1 = range(050)  
  3. Y1 = [num**2 for num in X1] # y = x^2 X2 = [0, 1] Y2 = [0, 1] # y = x  
  4.   
  5. Fig = plt.figure(figsize=(8,4)) # Create a `figure' instance  
  6. Ax = Fig.add_subplot(111# Create a `axes' instance in the figure  
  7. Ax.plot(X1, Y1, X2, Y2) # Create a Line2D instance in the axes  
  8.   
  9. Fig.show()   
  10. Fig.savefig("test.pdf")  
[matplotlib-绘制精美的图表]

[什么是 Matplotlib (面向对象绘图)]

[Python图表绘制:matplotlib绘图库入门]
皮皮blog



Matplotlib中的作图参数

a set of tables that show main properties and styles
在IPython中输入 "plt.plot?" 可以查看格式化字符串的详细配置。

线属性Line properties

PropertyDescriptionAppearancealpha (or a)alpha transparency on 0-1 scalefigures/alpha.pngantialiasedTrue or False - use antialised renderingfigures/aliased.pngfigures/antialiased.pngcolor (or c)matplotlib color argfigures/color.pnglinestyle (or ls)see Line properties linewidth (or lw)float, the line width in pointsfigures/linewidth.pngsolid_capstyleCap style for solid linesfigures/solid_capstyle.pngsolid_joinstyleJoin style for solid linesfigures/solid_joinstyle.pngdash_capstyleCap style for dashesfigures/dash_capstyle.pngdash_joinstyleJoin style for dashesfigures/dash_joinstyle.pngmarkersee Markers markeredgewidth (mew)line width around the marker symbolfigures/mew.pngmarkeredgecolor (mec)edge color if a marker is usedfigures/mec.pngmarkerfacecolor (mfc)face color if a marker is usedfigures/mfc.pngmarkersize (ms)size of the marker in pointsfigures/ms.png

颜色(color 简写为 c):

    蓝色: 'b' (blue)
    绿色: 'g' (green)
    红色: 'r' (red)
    蓝绿色(墨绿色): 'c' (cyan)
    红紫色(洋红): 'm' (magenta)
    黄色: 'y' (yellow)
    黑色: 'k' (black)
    白色: 'w' (white)
    灰度表示: e.g. 0.75 ([0,1]内任意浮点数)
    RGB表示法: e.g. '#2F4F4F' 或 (0.18, 0.31, 0.31)
    任意合法的html中的颜色表示: e.g. 'red', 'darkslategray'

遍历使用颜色:colors = plt.cm.Spectral(np.linspace(0, 1, len(unique_labels)))

[Colormaps]

线型Line styles(简写为 ls):

  • 实线: '-'
  • 虚线: '--'
  • 虚点线: '-.'
  • 点线: ':'
  • 点: '.'
Note: 后面的都是设置点型,感觉有多余的设计。
SymbolDescriptionAppearance-solid linefigures/linestyle--.png--dashed linefigures/linestyle---.png-.dash-dot linefigures/linestyle--dot.png:dotted linefigures/linestyle-:.png.pointsfigures/linestyle-dot.png,pixelsfigures/linestyle-,.pngocirclefigures/linestyle-o.png^triangle upfigures/linestyle-^.pngvtriangle downfigures/linestyle-v.png<triangle leftfigures/linestyle-<.png>triangle rightfigures/linestyle->.pngssquarefigures/linestyle-s.png+plusfigures/linestyle-+.pngxcrossfigures/linestyle-x.pngDdiamondfigures/linestyle-dd.pngdthin diamondfigures/linestyle-d.png1tripod downfigures/linestyle-1.png2tripod upfigures/linestyle-2.png3tripod leftfigures/linestyle-3.png4tripod rightfigures/linestyle-4.pnghhexagonfigures/linestyle-h.pngHrotated hexagonfigures/linestyle-hh.pngppentagonfigures/linestyle-p.png|vertical linefigures/linestyle-|.png_horizontal linefigures/linestyle-_.png

点型Markers(标记):

标记大小(markersize 简写为 ms):    markersize: 实数
标记边缘宽度(markeredgewidth 简写为 mew):    markeredgewidth:实数
标记边缘颜色(markeredgecolor 简写为 mec):    markeredgecolor:颜色选项中的任意值
标记表面颜色(markerfacecolor 简写为 mfc):    markerfacecolor:颜色选项中的任意值。   marker填充色
透明度(alpha):    alpha: [0,1]之间的浮点数
线宽(linewidth):    linewidth: 实数

设置marker显示的个数(marker数目太多时可以使用): markevery. You could decide on the x locations where you want the marks, use e.g. numpy.searchsorted to find which data points the locations fall between, and then interpolate between the neighboring points to find the y coordinates. [Plot with fewer markers than data points (or a better way to plot CDFs?)]

Note: 可以通过设置mfc='none', mec='r'使plot绘制空心园。

markers标记

SymbolDescriptionAppearance0tick leftfigures/marker-i0.png1tick rightfigures/marker-i1.png2tick upfigures/marker-i2.png3tick downfigures/marker-i3.png4caret leftfigures/marker-i4.png5caret rightfigures/marker-i5.png6caret upfigures/marker-i6.png7caret downfigures/marker-i7.pngocirclefigures/marker-o.pngDdiamondfigures/marker-dd.pnghhexagon 1figures/marker-h.pngHhexagon 2figures/marker-hh.png_horizontal linefigures/marker-_.png1tripod downfigures/marker-1.png2tripod upfigures/marker-2.png3tripod leftfigures/marker-3.png4tripod rightfigures/marker-4.png8octagonfigures/marker-8.pngppentagonfigures/marker-p.png^triangle upfigures/marker-^.pngvtriangle downfigures/marker-v.png<triangle leftfigures/marker-<.png>triangle rightfigures/marker->.pngdthin diamondfigures/marker-d.png,pixelfigures/marker-,.png+plusfigures/marker-+.png.pointfigures/marker-dot.pngssquarefigures/marker-s.png*starfigures/marker-*.png|vertical linefigures/marker-|.pngxcrossfigures/marker-x.pngr'$\sqrt{2}$'any latex expressionfigures/marker-latex.png

[Quick references]

[matplotlib中的作图参数]



坐标轴设定

Axis容器包括坐标轴的刻度线、刻度标签、坐标网格以及坐标轴标题等内容。刻度包括主刻度和副刻度,分别通过get_major_ticks()和get_minor_ticks()方法获得。每个刻度线都是一 个XTick或YTick对象,它包括实际的刻度线和刻度标签。Axis 对象提供了 get_ticklabels()和get_ticklines()方法,可以直接获得刻度标签和刻度线。
>>> plt.plot([1,2,3],[4,5,6])
>>>plt.show()
>>> axis = plt.gca().xaxis
>>> axis.get_ticklocs()#获得axis对象的刻度位置列表
array([ 1. ,  1.5,  2. ,  2.5,  3. ]) 
>>> axis.get_ticklabels() # 获得刻度标签列表
<a list of 5 Text major ticklabel objects>
>>> [x.get_text() for x in axis.get_ticklabels()]# 获得刻度的文本字符串
[u'1.0', u'1.5', u'2.0', u'2.5', u'3.0‘] 
获得X轴上表示主刻度线的列表,可看到X轴上共有10条刻度线:
>>>  axis.get_ticklines()
<a list of 10 Line2D ticklines objects>
由于没有副刻度线,因此副刻度线列表的长度为0:
>>> axis.get_ticklines(minor=True) # 获得副刻度线列表
<a list of 0 Line2D ticklines objects>
使用pyplot模块中的xticks()能够完成X轴上刻度标签的配置:
>>>plt.xticks(fontsize=16, color="red", rotation=45)

MatPlotLib中设置坐标轴主刻度标签和次刻度标签显示

{配置刻度线位置Locator类-控制刻度标签显示Formatter类}

用于计算副刻度位置的对象默认为 NullLocator,它不产生任何刻度线。而计算主刻度位置的对象为AutoLocator,它会根据当前的缩放等配置自动计算刻度的位置。
matplotlib提供了多种配置刻度线位置的Locator类,以及控制刻度标签显示的Formatter 类。

与刻度定位和文本格式化相关的类都在matplotlib.ticker模块中定义,载入了两个类:MultipleLocaton, FuncFormatter可以以指定值的整数倍为刻度放置主、副刻度线。
使用指定的函数计算刻度文本,它会将刻度值和刻度的序号作为参数传递给计算刻度文本的函数。

对于次刻度显示,如果要使用默认设置只要matplotlib.pyplot.minorticks_on()  

设置刻度示例

示例1

from matplotlib import ticker, pyplot as plt
... ...
ax = plt.gca()
ax.yaxis.set_minor_locator(ticker.MultipleLocator(.5)) # 将此y轴次刻度标签设置为0.5的倍数
ax.yaxis.set_minor_formatter(ticker.FormatStrFormatter('%1.1f')) # 设置y轴次标签文本格式
ax.yaxis.set_major_formatter(ticker.FormatStrFormatter('%1.1f')) # 设置y轴主标签文本的格式
ax.xaxis.grid(True, which='major') # x坐标轴的网格使用主刻度
ax.yaxis.grid(True, which='minor') # y坐标轴的网格使用次刻度

上面的示例中,实际主刻度标签和副刻度标签文本是重叠的,如果格式不一样就会显示不好,这样可能需要下面的FuncFormatter。

示例2

下面的程序设置X轴的主刻度为π/4,副刻度为π/20,并且主刻度上的标签用数学符号显示π。
from matplotlib.ticker import MultipleLocator, FuncFormatter
ax.xaxis.set_major_locator( MultipleLocator(np.pi/4) ) 
ax.xaxis.set_minor_locator( MultipleLocator(np.pi/20) )
ax.xaxis.set_major_formatter( FuncFormatter( pi_formatter ) ) 
def pi_formatter(x, pos): 
    m = np.round(x / (np.pi/4))
    n = 4
    while m!=0 and m%2==0: m, n = m//2, n//2
    if m == 0:
        return "0"
    if m == 1 and n == 1:
        return "$\pi$"
    if n == 1:
        return r"$%d \pi$" % m
    if m == 1:
        return r"$\frac{\pi}{%d}$" % n
    return r"$\frac{%d \pi}{%d}$" % (m,n)

ps:

选择是否显示刻度值:x轴上,1为下,2为上;y轴上,1为左,2为右;
for tick in ax.xaxis.get_major_ticks():
    tick.label1On = True
    tick.label2On = False
for tick in ax.yaxis.get_major_ticks():
    tick.label1On = False
    tick.label2On = False

选择如何显示刻度
ax.xaxis.set_ticks_position(‘none’)
ax.yaxis.set_ticks_position(‘right’)

完全自定义坐标轴刻度及刻度值
ax.set_xticks([-250, -200, -150, -100, -50, 0, 50, 100, 150, 200])
ax.set_xticklabels([‘-250’, ”, ‘-150’, ”, ‘-50′, ”, ’50’, ”, ‘150’, ”])
ax.set_yticks([-40, -20, 0, 20, 40, 60, 80])
ax.set_yticklabels([”, ”, ”, ”, ”, ”, ”])

分别设置x轴和y轴上刻度值的字体大小
for tick in ax.xaxis.get_major_ticks():
    tick.label1.set_fontsize(18)
for tick in ax.yaxis.get_major_ticks():
    tick.label1.set_fontsize(18)

这也可以设置刻度值字体大小
matplotlib.rc(‘xtick’, labelsize=20)
matplotlib.rc(‘ytick’, labelsize=20)

皮皮blog



配置属性

matplotlib所绘制的图的每个组成部分都对应有一个对象,我们可以通过调用这些对象的属性设置方法set_*或者pyplot的属性设置函数setp设置其属性值。

设置对象的属性

例如plot函数返回一个 matplotlib.lines.Line2D 对象的列表,下面的例子显示如何设置Line2D对象的属性:

>>> import numpy as np>>> import matplotlib.pyplot as plt>>> x = np.arange(0, 5, 0.1)>>> line, = plt.plot(x, x*x) # plot返回一个列表,通过line,获取其第一个元素>>> # 调用Line2D对象的set_*方法设置属性值>>> line.set_antialiased(False)
>>> # 同时绘制sin和cos两条曲线,lines是一个有两个Line2D对象的列表>>> lines = plt.plot(x, np.sin(x), x, np.cos(x)) #>>> # 调用setp函数同时配置多个Line2D对象的多个属性值>>> plt.setp(lines, color="r", linewidth=2.0)

这段例子中,通过调用Line2D对象line的set_antialiased方法,关闭对象的反锯齿效果。或者通过调用plt.setp函数配置多个Line2D对象的颜色和线宽属性。

获取对象的属性值

同样我们可以通过调用Line2D对象的get_*方法,或者plt.getp函数获取对象的属性值:

>>> line.get_linewidth()1.0>>> plt.getp(lines[0], "color") # 返回color属性'r'>>> plt.getp(lines[1]) # 输出全部属性alpha = 1.0animated = Falseantialiased or aa = Trueaxes = Axes(0.125,0.1;0.775x0.8)... ...

Note:getp函数只能对一个对象进行操作,它有两种用法:

  • 指定属性名:返回对象的指定属性的值
  • 不指定属性名:打印出对象的所有属性和其值

获取当前的绘图对象plt.gcf()

matplotlib的整个图表为一个Figure对象,此对象在调用plt.figure函数时返回,我们也可以通过plt.gcf函数获取当前的绘图对象

>>> f = plt.gcf()>>> plt.getp(f)alpha = 1.0animated = False...

Figure对象axes属性plt.gca()

Figure对象有一个axes属性,其值为AxesSubplot对象的列表,每个AxesSubplot对象代表图表中的一个子图,前面所绘制的图表只包含一个子图,当前子图也可以通过plt.gca获得

>>> plt.getp(f, "axes")[<matplotlib.axes.AxesSubplot object at 0x05CDD170>]>>> plt.gca()<matplotlib.axes.AxesSubplot object at 0x05CDD170>

获取对象的各种属性plt.getp

用plt.getp可以发现AxesSubplot对象有很多属性,例如它的lines属性为此子图所包括的 Line2D 对象列表:

>>> alllines = plt.getp(plt.gca(), "lines")>>> alllines<a list of 3 Line2D objects>>>> alllines[0] == line # 其中的第一条曲线就是最开始绘制的那条曲线True

通过这种方法我们可以很容易地查看对象的属性和它们之间的包含关系,找到需要配置的属性。


配置文件

绘制一幅图需要对许多对象的属性进行配置,例如颜色、字体、线型等等。我们在绘图时,并没有逐一对这些属性进行配置,许多都直接采用了matplotlib的缺省配置。
matplotlib将这些缺省配置保存在一个名为“matplotlibrc”的配置文件中,通过修改配置文件,我们可以修改图表的缺省样式。

在matplotlib中可以使用多个“matplotlibrc”配置文件,它们的搜索顺序如下,顺序靠前的配置文件将会被优先采用。

  • 当前路径:程序的当前路径。
  • 用户配置路径:通常在用户文件夹的“.matplotlib”目录下,可以通过环境变量MATPLOTLIBRC修改它的位置。
  • 系统配置路径:保存在matplotlib的安装目录下的mpl-data中。

通过下面的语句可以获取用户配置路径:

>>> import matplotlib>>> matplotlib.get_configdir()'C:\\Documents and Settings\\用户名\\.matplotlib'

通过下面的语句可以获得目前使用的配置文件的路径:

>>> import matplotlib>>> matplotlib.matplotlib_fname()'C:\\Python26\\lib\\site-packages\\matplotlib\\mpl-data\\matplotlibrc'

由于在当前路径和用户配置路径中都没有找到配置文件,因此最后使用的是系统配置路径下的配置文件。如果读者将matplotlibrc复制一份到脚本的当前目录(例如,c:\zhang\doc)下:

>>> import os>>> os.getcwd()'C:\\zhang\\doc'

复制配置文件之后再查看配置文件的路径,就会发现它变为了当前目录下的配置文件:

>>> matplotlib.matplotlib_fname()'C:\\zhang\\doc\\matplotlibrc'

如果读者使用文本编辑器打开此配置文件,就会发现它实际上是一个字典。为了对众多的配置进行区分,字典的键根据配置的种类,用“.”分为多段。

配置文件的读入可以使用rc_params(),它返回一个配置字典:

>>> matplotlib.rc_params(){'agg.path.chunksize': 0, 'axes.axisbelow': False, 'axes.edgecolor': 'k', 'axes.facecolor': 'w', ... ...

在matplotlib模块载入时会调用rc_params(),并把得到的配置字典保存到rcParams变量中:

>>> matplotlib.rcParams{'agg.path.chunksize': 0,'axes.axisbelow': False,... ...

matplotlib将使用rcParams字典中的配置进行绘图。用户可以直接修改此字典中的配置,所做的改变会反映到此后创建的绘图元素。例如下面的代码所绘制的折线将带有圆形的点标识符:

>>> matplotlib.rcParams["lines.marker"] = "o">>> plt.plot([1,2,3,2])>>> plt.show()

为了方便对配置字典进行设置,可以使用rc()。下面的例子同时配置点标识符、线宽和颜色:

>>> matplotlib.rc("lines", marker="x", linewidth=2, color="red")

如果希望恢复到缺省的配置(matplotlib载入时从配置文件读入的配置),可以调用rcdefaults()。

>>> matplotlib.rcdefaults()

如果手工修改了配置文件,希望重新从配置文件载入最新的配置,可以调用:

>>> matplotlib.rcParams.update( matplotlib.rc_params() )
通过pyplot模块也可以使用rcParams、rc和rcdefaults。
皮皮blog



图像载入和显示

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

plt.imread()

从图像文件读入数据,得到一个表示图像的NumPy数组。它的第一个参数是文件名或文件对象,format参数指定图像类型,如果省略,就由文件的扩展名决定图像类型。 
对于灰度图像,它返回一个形状为(M,N)的数组;对于彩色图像,返冋形状为(M,N,C)的数组。 其中,M为图像的高度,N为图像的宽度,C为3或4,表示图像的通道数。
程序从“lena.jpg” 中读入图像数据:
>>>img = plt.imread(“lena.jpg")
>>> img.shape 
>>> (393, 512, 3)
>>> img.dtype
dtype(’uint8’)

plt.imshow

Display an image on the axes.
    matplotlib.pyplot.imshow(X, cmap=None, norm=None, aspect=None, interpolation=None, alpha=None, vmin=None, vmax=None, origin=None, extent=None, shape=None, filternorm=1, filterrad=4.0, imlim=None, resample=None, url=None, hold=None, data=None, **kwargs)
X : array_like, shape (n, m) or (n, m, 3) or (n, m, 4)
vmin, vmax : scalar, optional, default: None
    vmin and vmax are used in conjunction with norm to normalize luminance data. Note if you pass a norm instance, your settings for vmin and vmax will be ignored.

>>> plt.imshow(img〉#注意图像是上下颠倒的

#plt.imshow(img[::-1]) #反转图像数组的第0轴,不好理解?
>>> plt.imshow(img, origin=”lower”) # 让图表的原点在左下角
得到的数组img是一个形状为(393,512,3)的单字节无符号整数数组。这是因为通常使用的图像都是采用单字节分别保存每个像素的红、绿、蓝三个通道的分量。
注意,从JPG图像中读入的数据是上下颠倒的,为了正常显示图像,可以将数组的第0轴反转,或者设置imshow()的origin参数为“lower”,从而让所显示图表的原点在左下角。

如果三维数组的元素类型为浮点数,那么元素的取值范围为0.0到1.0,与颜色值0到255 对应,超出这个范围可能会出现颜色异常的像素。
>>> img = img[: :-1]
>>> plt.imshow(img*1.0) #取值范围为0.0到255.0的浮点数组,不能正确显示颜色 
>>> plt.imshow(img/255.0) #取值范围为0.0到1.0的浮点数组,能正确显示颜色
>>> plt.imshow(np.clip(img/200.0, 0, 1)> # 使用 clip()限制取值范围,整个图像变亮
如果imshow()的参数是二维数组,就使用颜色映射表决定每个像素的颜色。下面显示图像 中的红色通道:
>>> plt.imshow(img[:,:,0])
显示效果比较吓人,因为默认的图像映射将最小值映射为蓝色、将最大值映射为红色. 可以使用colorbar()将颜色映射表在图表中显示出来:
>>> plt.colorbar()
通过imshow()的cmap参数可以修改显示图像时所采用的颜色映射表。颜色映射表是一个 ColorMap对象,matplotlib中已经预先定义好了很多颜色映射表,可通过下面的语句找到这 些颜色映射表的名字:
>>> import matplotlib.cm as cm 
>>> cm._cmapnames
[‘Spectral’,’copper’, ‘RdYlGn', ‘Set2’,’ sumner’, ’spring’,’gist_ncar’,…]
下面使用名为copper的颜色映射表显示图像的红色通道,很有老照片的味道: 
>>>plt.imshow(img[:,:,0],cmap=cm.copper)
还可以使用imshow()显示任意的二维数据,例如下面的程序使用图像直观地显示了二元函数:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

y, x = np.ogrid[-2:2:200j, -2:2:200j]
z = x * np.exp( - x**2 - y**2)

extent = [np.min(x), np.max(x), np.min(y), np.max(y)]
plt.figure(figsize=(10,3))
plt.subplot(121)
plt.imshow(z, extent=extent, origin="lower") 
plt.colorbar()
plt.subplot(122)
plt.imshow(z, extent=extent, cmap=cm.gray, origin="lower")
plt.colorbar()

plt.show()
imshow()的extent参数,图表的X、Y轴的刻度标签所指定的范围.

[matplotlib.pyplot.imshow]

皮皮blog

matplotlib绘图实例

matplotlib绘图进阶

from:http://blog.csdn.net/pipisorry/article/details/37742423

ref: matplotlib.pyplot

python matplotlib中所有模块查询:Python Module Index

matplotlib所有类和类中的函数查询:Index

绘图命令集合 : Plotting commands summary

Gallerys : http://matplotlib.org/1.4.3/gallery.html

Matplotlib教程(点击对应的图可见源码,复制可直接使用): Matplotlib tutorial

关于各个部件和属性:Figures, Subplots, Axes and Ticks

用Python做科学计算-基础篇——使用pyplot模块绘图

matplotlib的一些常用命令和技巧

Matplotlib for Python Developers

Matplotlib Tutorial(译)


0 0
原创粉丝点击