搜档网
当前位置:搜档网 › matplotlib模块

matplotlib模块

matplotlib模块
matplotlib模块

1. 导入模块

导入matplotlib的子模块

import matplotlib.pyplot as plt

import numpy as np

2. 获取数据对象

给出x,y两个数组[Python列表],注意两个列表的元素个数必须相同,否则会报错x=np.array([1,2,3,4,])

y=x*2

3. 调用画图方法

调用pyplot模块的绘图方法画出图像,基本的画图方法有:plot(将各个点连成曲线图)、scatter(画散点图),bar(画条形图)还有更多方法。

1) 新建图画板对象

# 使用figure()函数重新申请一个figure对象

# 注意,每次调用figure的时候都会重新申请一个figure对象

# 第一个参数表示的是编号,第二个表示的是图表的长宽

plt.figure(num = 2, figsize=(8, 5))

2) 调用画图种类模式的方法

#color='red'表示线颜色,inewidth=1.0表示线宽,linestyle='--'表示线样式

L1 , =plt.plot(x,y,color="r",linewidth=1.0, linestyle='--', label=”曲线图”)

# s表示点的大小,默认rcParams['lines.markersize']**2

L2 , =plt.scatter(x,y,color="r",s=12,linewidth=1.0,linestyle='--',lable=”散点图”)

L3 , =plt.bar(x,y, color='green')

3) 设置图标签

# 使用legend绘制多条曲线

plt.legend(handles=[L1,L2], labels=[”曲线图”, ”散点图”], loc=”best”)

或者:

plt.plot(x,y,lable=”label”)

plt.lengend()

4) 设置轴线的lable(标签)

plt.xlabel('longitude')#说明x轴表示经度

plt.ylabel('latitude')#说明y轴表示纬度

5) 设置轴线取值参数范围

plt.axis([-1,2,1,3]) # x和y参数范围

plt.xlim((-1, 2)) # x参数范围

plt.ylim((1, 3)) # y参数范围

6) 设置轴线点位置的提示

# 设置点的位置

# 为点的位置设置对应的文字。

# 第一个参数是点的位置,第二个参数是点的文字提示。

plt.xticks(x,[r"one",r"two",r"three",r"four"])

plt.yticks(y,[r"first",r"second",r"thrid",r"fourth"])

7) 设置边框颜色

# gca = 'get current axis'

ax = plt.gca()

# 将右边和上边的边框(脊)的颜色去掉

ax.spines['right'].set_color('none')

ax.spines['top'].set_color('none')

8) 绑定x轴和y轴

ax.xaxis.set_ticks_position('bottom')

ax.yaxis.set_ticks_position('left')

9) 定义x轴和y轴的位置

ax.spines['bottom'].set_position(('data', 0))

ax.spines['left'].set_position(('data', 0))

10) 设置关键位置的提示信息

annotate语法说明:annotate(s='str' ,xy=(x,y) ,xytext=(l1,l2) ,..) s 为注释文本内容

xy 为被注释的坐标点

xytext 为注释文字的坐标位置

xycoords 参数如下:

figure points points from the lower left of the figure 点在图左下方

figure pixels pixels from the lower left of the figure 图左下角的像素

figure fraction fraction of figure from lower left 左下角数字部分

axes points points from lower left corner of axes 从左下角点的坐标

axes pixels pixels from lower left corner of axes 从左下角的像素坐标

axes fraction fraction of axes from lower left 左下角部分

data use the coordinate system of the object being annotated(default) 使用的坐标系统被注释的对象(默认)

polar(theta,r) if not native ‘data’ coordinates t

extcoords 设置注释文字偏移量

参数| 坐标系|

| 'figure points' | 距离图形左下角的点数量|

| 'figure pixels' | 距离图形左下角的像素数量|

| 'figure fraction' | 0,0 是图形左下角,1,1 是右上角|

| 'axes points' | 距离轴域左下角的点数量|

| 'axes pixels' | 距离轴域左下角的像素数量|

| 'axes fraction' | 0,0 是轴域左下角,1,1 是右上角|

| 'data' | 使用轴域数据坐标系|

arrowprops #箭头参数,参数类型为字典dict

width the width of the arrow in points 点箭头的宽度

headwidth the width of the base of the arrow head in points 在点的箭头底座的宽度

headlength the length of the arrow head in points 点箭头的长度

shrink fraction of total length to ‘shrink’ from both ends总长度为分数“缩水”从两端

facecolor 箭头颜色

bbox给标题增加外框,常用参数如下:

boxstyle方框外形

facecolor(简写fc)背景颜色

edgecolor(简写ec)边框线条颜色

edgewidth边框线条大小

bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc为facecolor,ec为edgecolor,lw为lineweight

例子:

for xy in zip(x, y):

plt.annotate("(%s,%s)" % xy, xy=xy, xytext=(-20, 10), textcoords='offset points')

11) 设置图的标题

title常用参数:

fontsize设置字体大小,默认12,可选参数['xx-small', 'x-small', 'small', 'medium',

'large','x-large', 'xx-large']

fontweight设置字体粗细,可选参数['light', 'normal', 'medium', 'semibold', 'bold', 'heavy', 'black']

fontstyle设置字体类型,可选参数[ 'normal' | 'italic' | 'oblique' ],italic斜体,oblique倾斜

verticalalignment设置水平对齐方式,可选参数: 'center' , 'top' , 'bottom' ,'baseline'

horizontalalignment设置垂直对齐方式,可选参数:left,right,center

rotation(旋转角度)可选参数为:vertical,horizontal 也可以为数字

alpha透明度,参数值0至1之间

backgroundcolor标题背景颜色

bbox给标题增加外框,常用参数如下:

boxstyle方框外形

facecolor(简写fc)背景颜色

edgecolor(简写ec)边框线条颜色

edgewidth边框线条大小

title例子:

plt.title('Interesting Graph',fontsize='large',fontweight='bold') 设置字体大小与格式

plt.title('Interesting Graph',color='blue') 设置字体颜色

plt.title('Interesting Graph',loc ='left') 设置字体位置

plt.title('Interesting Graph',verticalalignment='bottom') 设置垂直对齐方式

plt.title('Interesting Graph',rotation=45) 设置字体旋转角度

plt.title('Interesting',bbox=dict(facecolor='g', edgecolor='blue', alpha=0.65 )) 标题边框

plt.title('Title')

12) 设置图的文本

text语法说明

text(x,y,string,fontsize=15,verticalalignment="top",horizontalalignment="right")

x,y:表示坐标值上的值

string:表示说明文字

fontsize:表示字体大小

verticalalignment:垂直对齐方式,参数:[ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]

horizontalalignment:水平对齐方式,参数:[ ‘center’ | ‘right’ | ‘left’ ]

xycoords选择指定的坐标轴系统:

figure points points from the lower left of the figure 点在图左下方

figure pixels pixels from the lower left of the figure 图左下角的像素

figure fraction fraction of figure from lower left 左下角数字部分

axes points points from lower left corner of axes 从左下角点的坐标

axes pixels pixels from lower left corner of axes 从左下角的像素坐标

axes fraction fraction of axes from lower left 左下角部分

data use the coordinate system of the object being annotated(default) 使用的坐标系统被注释的对象(默认)

polar(theta,r) if not native ‘data’ coordinates t

arrowprops #箭头参数,参数类型为字典dict

width the width of the arrow in points 点箭头的宽度

headwidth the width of the base of the arrow head in points 在点的箭头底座的宽度

headlength the length of the arrow head in points 点箭头的长度

shrink fraction of total length to ‘shrink’ from both ends总长度为分数“缩水”从两端

facecolor 箭头颜色

bbox给标题增加外框,常用参数如下:

boxstyle方框外形

facecolor(简写fc)背景颜色

edgecolor(简写ec)边框线条颜色

edgewidth边框线条大小

bbox=dict(boxstyle='round,pad=0.5', fc='yellow', ec='k',lw=1 ,alpha=0.5) #fc为facecolor,ec为edgecolor,lw为lineweight

例子:

plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',va='top',wrap=True)

plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)

13) 展现结果图

调用pyplot的show方法,显示结果。

plt.show()

4. 解析

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

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

subplot(numRows, numCols, plotNum)

subplot将整个绘图区域等分为numRows行* numCols列个子区域,然后按照从左到右,

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

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

#coding=utf-8

import numpy as np

import matplotlib.pyplot as plt

plt.figure(1) # 创建图表1

plt.figure(2) # 创建图表2

ax1 = plt.subplot(211) # 在图表2中创建子图1

ax2 = plt.subplot(212) # 在图表2中创建子图2

x = np.linspace(0, 3, 100)

for i in xrange(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()

在图表中显示中文

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

在程序中直接指定字体。

在程序开头修改配置字典rcParams。

修改配置文件。

面向对象画图

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

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

创建Figure对象

用Figure对象创建一个或者多个Axes或者Subplot对象

调用Axies等对象的方法创建各种简单类型的Artists

import matplotlib.pyplot as plt

X1 = range(0, 50)

Y1 = [num**2 for num in X1] # y = x^2

X2 = [0, 1]

Y2 = [0, 1] # y = x

Fig = plt.figure(figsize=(8,4)) # Create a `figure' instance

Ax = Fig.add_subplot(111) # Create a `axes' instance in the figure

Ax.plot(X1, Y1, X2, Y2) # Create a Line2D instance in the axes

Fig.show()

Fig.savefig("test.pdf")

1) figure语法及操作

figure(num=None, figsize=None, dpi=None, facecolor=None, edgecolor=None, frameon=True)

num:图像编号或名称,数字为编号,字符串为名称,可以通过该参数激活不同的画布figsize:指定figure的宽和高,单位为英寸;

dpi参数指定绘图对象的分辨率,即每英寸多少个像素,缺省值为80。相同的figsize,dpi 越大画布越大

facecolor:背景颜色

edgecolor:边框颜色

frameon:是否显示边框,默认值True为绘制边框,如果为False则不绘制边框

import matplotlib.pyplot as plt

创建自定义图像

fig=plt.figure(figsize=(4,3),facecolor='blue')

plt.show()

2) subplot创建单个子图

subplot(nrows,ncols,sharex,sharey,subplot_kw,**fig_kw)

subplot可以规划figure划分为n个子图,但每条subplot命令只会创建一个子图,参考下面例子。

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 100)

#子图1

plt.subplot(221)

plt.plot(x, x)

#子图2

plt.subplot(222)

plt.plot(x, -x)

#子图3

plt.subplot(223)

plt.plot(x, x ** 2)

plt.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)

#子图4

plt.subplot(224)

plt.plot(x, np.log(x))

plt.show()

3) subplots创建多个子图subplots参数与subplots相似

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 100)

#划分子图

fig,axes=plt.subplots(2,2)

ax1=axes[0,0]

ax2=axes[0,1]

ax3=axes[1,0]

ax4=axes[1,1]

#子图1

ax1.plot(x, x)

#子图2

ax2.plot(x, -x)

#子图3

ax3.plot(x, x ** 2)

ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)

#子图4

ax4.plot(x, np.log(x))

plt.show()

4) add_subplot新增子图

add_subplot是面对象figure类api,pyplot api中没有此命令add_subplot的参数与subplots的相似

import numpy as np

import matplotlib.pyplot as plt

x = np.arange(0, 100)

#新建figure对象

fig=plt.figure()

#新建子图1

ax1=fig.add_subplot(2,2,1)

ax1.plot(x, x)

#新建子图3

ax3=fig.add_subplot(2,2,3)

ax3.plot(x, x ** 2)

ax3.grid(color='r', linestyle='--', linewidth=1,alpha=0.3)

#新建子图4

ax4=fig.add_subplot(2,2,4)

ax4.plot(x, np.log(x))

plt.show()

5) add_axes新增子区域

add_axes为新增子区域,该区域可以座落在figure内任意位置,且该区域可任意设置大小add_axes参数可参考官方文档:

https://www.sodocs.net/doc/bd12374116.html,/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure import numpy as np

import matplotlib.pyplot as plt

#新建figure

fig = plt.figure()

# 定义数据

x = [1, 2, 3, 4, 5, 6, 7]

y = [1, 3, 4, 2, 5, 8, 6]

#新建区域ax1

#figure的百分比,从figure 10%的位置开始绘制, 宽高是figure的80%

left, bottom, width, height = 0.1, 0.1, 0.8, 0.8

# 获得绘制的句柄

ax1 = fig.add_axes([left, bottom, width, height])

ax1.plot(x, y, 'r')

ax1.set_title('area1')

#新增区域ax2,嵌套在ax1内

left, bottom, width, height = 0.2, 0.6, 0.25, 0.25

# 获得绘制的句柄

ax2 = fig.add_axes([left, bottom, width, height])

ax2.plot(x, y, 'b')

ax2.set_title('area2')

plt.show()

5. Matplotlib.pyplot和matplotlib.pylab的区别

pylab结合了pyplot和numpy,对交互式使用来说比较方便,既可以画图又可以进行简单的计算。但是,对于一个项目来说,建议分别倒入使用

6. matplotlib中文显示

import matplotlib.pyplot as plt

a) FontProperties方法

#coding=utf-8

import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties

fig = plt.figure()

font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=14) plt.xlabel(u"x轴", fontproperties=font)

plt.show()

b) fontproperties方法

#coding=utf-8

import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties

fig = plt.figure()

plt.ylabel(u"y轴", fontproperties="SimHei")

plt.show()

c) rcParams方法

#coding=utf-8

import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties

fig = plt.figure()

plt.rcParams['font.sans-serif'] = ['SimHei']

plt.rcParams['axes.unicode_minus'] = False

plt.xlabel(u"x轴")

plt.show()

d) rc方法

#coding=utf-8

import matplotlib.pyplot as plt

from matplotlib.font_manager import FontProperties

fig = plt.figure()

font = {'family' : 'SimHei','weight' : 'bold','size' : '16'}

plt.rc('font', **font)

plt.rc('axes', unicode_minus=False)

plt.xlabel(u"x轴")

plt.show()

方式二用时才设置,且不会污染全局字体设置,更灵活

方式三、方式四不需要对字体路径硬编码,而且一次设置,多次使用,更方便。一些中文字体的英文名

宋体SimSun

黑体SimHei

微软雅黑Microsoft YaHei

微软正黑体Microsoft JhengHei

新宋体NSimSun

新细明体PMingLiU

细明体MingLiU

标楷体DFKai-SB

仿宋FangSong

楷体KaiTi

隶书:LiSu

幼圆:YouYuan

华文细黑:STXihei

华文楷体:STKaiti

华文宋体:STSong

华文中宋:STZhongsong

华文仿宋:STFangsong

方正舒体:FZShuTi

方正姚体:FZYaoti

华文彩云:STCaiyun

华文琥珀:STHupo

华文隶书:STLiti

华文行楷:STXingkai

华文新魏:STXinwei

6) Pyplot绘图结构

Aritists

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创建图表的标准流程如下:

l 创建Figure对象;

l 用Figure对象创建一个或者多个Axes或者Subplot对象;

l 调用Axies等对象的方法创建各种简单类型的Artists。

a) Figure

Figure代表一个绘制面板,其中可以包涵多个Axes(即多个图表)。

b) Axes

Axes表示一个图表

一个Axes包涵:titlek, xaxis, yaxis

c) Axis

坐标轴

7) Pyplot绘图结构的Artist的属性

下面是Artist对象都具有的一些属性:

alpha : 透明度,值在0到1之间,0为完全透明,1为完全不透明

animated : 布尔值,在绘制动画效果时使用

axes : 此Artist对象所在的Axes对象,可能为None

clip_box : 对象的裁剪框

clip_on : 是否裁剪

clip_path : 裁剪的路径

contains : 判断指定点是否在对象上的函数

figure : 所在的Figure对象,可能为None

label : 文本标签

picker : 控制Artist对象选取

transform : 控制偏移旋转

visible : 是否可见

zorder : 控制绘图顺序

Artist对象的所有属性都通过相应的get_* 和set_* 函数进行读写

fig.set_alpha(0.5*fig.get_alpha())

如果你想用一条语句设置多个属性的话,可以使用set函数:

fig.set(alpha=0.5, zorder=2)

使用matplotlib.pyplot.getp 函数可以方便地输出Artist对象的所有属性名和值。

>>> plt.getp(fig.patch)

aa = True

alpha = 1.0

animated = False

antialiased or aa = True

a) Figure

如前所述,Figure是最大的一个Aritist,它包括整幅图像的所有元素,背景是一个Rectangle 对象,用Figure.patch属性表示。

通过调用add_subplot或者add_axes方法往图表中添加Axes(子图)。

PS:这两个方法返回值类型不同

>>> fig = plt.figure()

>>> ax1 = fig.add_subplot(211)

>>> ax2 = fig.add_axes([0.1, 0.1, 0.7, 0.3])

>>> ax1

>>> ax2

>>> fig.axes

[,

]

为了支持pylab中的gca()等函数,Figure对象内部保存有当前轴的信息,因此不建议直接对Figure.axes属性进行列表操作,而应该使用add_subplot, add_axes, delaxes等方法进行添加和删除操作。

fig = plt.figure()

ax1 = fig.add_axes([0.1, 0.45, 0.8, 0.5])

ax2 = fig.add_axes([0.1, 0.1, 0.8, 0.2])

plt.show()

Figure对象可以拥有自己的文字、线条以及图像等简单类型的Artist。缺省的坐标系统为像素点,但是可以通过设置Artist对象的transform属性修改坐标系的转换方式。最常用的Figure对象的坐标系是以左下角为坐标原点(0,0),右上角为坐标(1,1)。下面的程序创建并添加两条直线到fig中:

>>> from matplotlib.lines import Line2D

>>> fig = 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="g")

>>> fig.lines.extend([line1, line2])

>>> fig.show()

---------------------

在Figure对象中手工绘制直线

注意为了让所创建的Line2D对象使用fig的坐标,我们将fig.TransFigure赋给Line2D对象的transform属性;为了让Line2D对象知道它是在fig对象中,我们还设置其figure属性为fig;最后还需要将创建的两个Line2D对象添加到fig.lines属性中去。

Figure对象有如下属性包含其它的Artist对象:

axes : Axes对象列表

patch : 作为背景的Rectangle对象

images : FigureImage对象列表,用来显示图片

legends : Legend对象列表

lines : Line2D对象列表

patches : patch对象列表

texts : Text对象列表,用来显示文字

b) Axes

Axes容器是整个matplotlib库的核心,它包含了组成图表的众多Artist对象,并且有许多方法函数帮助我们创建、修改这些对象。和Figure一样,它有一个patch属性作为背景,

当它是笛卡尔坐标时,patch属性是一个Rectangle对象;

当它是极坐标时,patch属性则是Circle对象。

当你调用Axes的绘图方法(例如plot),它将创建一组Line2D对象,并将所有的关键字参数传递给这些Line2D对象,并将它们添加进Axes.lines属性中,最后返回所创建的Line2D 对象列表:

x1 = np.linspace(0.0, 5.0)

相关主题