0. 图形窗口
plt. figure(
'' ,
figsize= ( 80 , 20 ) ,
dpi= 80 ,
facecolor= ''
)
plt. show( )
plt. title( title, fontsize= 12 )
plt. xlabel( x_label_str, fontsize= 12 )
plt. xlabel( y_label_str, fontsize= 12 )
plt. tick_params( . . . , labelsize= 8 , . . . )
"""
- or solid 粗线
-- or dashed 虚线
-. or dashdot 点虚线
: or dotted 点线
"""
plt. grid( liestyle= '' )
plt. tight_layout( )
在当前窗口构建多个窗口,窗口名不能相同,否则会覆盖
plt. figure( 'testA' , facecolor= 'red' )
plt. figure( 'testB' , facecolor= 'blue' )
plt. figure( 'testC' , facecolor= 'yellow' )
plt. figure( 'testD' , facecolor= 'green' )
plt. title( 'testA' , fo)
plt. show( )
1. 子图
矩阵式布局
from matplotlib import pyplot as plt
plt. figure( 'Subplot Layout' , facecolor= 'lightgray' )
"""
拆分矩阵
rows: 行数
cols: 列数
num: 编号
"""
plt. subplot( rows, cols, num)
plt. subplot( 3 , 3 , 5 )
plt. subplt( 335 )
plt. polot( )
plt. subplot( 3 , 3 , 3 )
plt. plot( )
from matplotlib import pyplot as plt
plt. figure( 'Subplot' , facecolor= 'lightgray' )
for i in range ( 1 , 10 ) :
plt. subplot( 3 , 3 , i)
"""
text 显示文本
0.5 横坐标
0.5 纵坐标
i 显示文本
size 文本字体大小
ha 水平居中
va 垂直居中
"""
plt. text( 0.5 , 0.5 , i, size= 36 , ha= 'center' , va= 'center' )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. tight_layout( )
plt. show( )
网格式布局
from matplotlib import pyplot as plt
from matplotlib import gridspec as mg
plt. figure( 'Grid Layout' , facecolor= 'lightgray' )
"""
调用GridSpec方法差分网格式布局
rows 行数
cols 列数
gs = mg.GridSpec(rows, cols) 拆分成3行3列
"""
gs = mg. GridSpec( 3 , 3 )
plt. subplot( gs[ 0 , : 2 ] )
plt. text( 0.5 , 0.5 , '1' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. subplot( gs[ : 2 , 2 : 3 ] )
plt. text( 0.5 , 0.5 , '2' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. subplot( gs[ 1 : 3 , 0 ] )
plt. text( 0.5 , 0.5 , '4' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. subplot( gs[ 2 , 1 : 3 ] )
plt. text( 0.5 , 0.5 , '5' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. subplot( gs[ 1 , 1 ] )
plt. text( 0.5 , 0.5 , '3' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. tight_layout( )
plt. show( )
自由布局
from __future__ import unicode_literals
from matplotlib import pyplot as plt
plt. figure( 'Free Layout' , facecolor= 'lightgray' )
plt. axes( [ 0.1 , 0.1 , 0.3 , 0.4 ] )
plt. text( 0.5 , 0.5 , '1' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. axes( [ 0.1 , 0.5 , 1.0 , 0.5 ] )
plt. text( 0.5 , 0.5 , '2' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. axes( [ 0.4 , 0.1 , 0.7 , 0.4 ] )
plt. text( 0.5 , 0.5 , '3' , ha= 'center' , va= 'center' , size= 36 )
plt. xticks( [ ] )
plt. yticks( [ ] )
plt. show( )
2. 刻度定位器
ax = plt. gca( )
ax. xaxis. set_major_localtor( plt. NullLocator( ) )
ax. xaxis. set_minor_locator( plt. MultipileLocator( ) )
from __future__ import unicode_literals
from matplotlib import pyplot as plt
plt. figure( 'Locators' , facecolor= 'lightgray' )
ax = plt. gca( )
ax. spines[ 'left' ] . set_color( 'none' )
ax. spines[ 'top' ] . set_color( 'none' )
ax. spines[ 'right' ] . set_color( 'none' )
plt. yticks( [ ] )
plt. xlim( 1 , 10 )
ax. spines[ 'bottom' ] . set_position( 'center' )
ma_loc = plt. MultipleLocator( 1 )
ax. xaxis. set_major_locator( ma_loc)
mi_loc = plt. MultipleLocator( 0.1 )
ax. xaxis. set_minor_locator( mi_loc)
plt. show( )
plt. NullLocator( )
plt. MaxNLocator( nbins= 3 )
plt. FixedLocator( locs= [ 0 , 2.5 , 5 , 7.5 , 10 ] )
plt. AutoLocator( )
plt. IndexLocator( offset= 0.5 , base= 1.5 )
plt. MultipleLocator( )
plt. LinearLocator( numticks= 21 )
plt. LogLocator( base= 2 )
3. 刻度网格线
ax = plt. gca( )
ax. grid(
which= '' ,
axis= '' ,
linewidth= 1 ,
linestyle= '' ,
color= '' ,
alpha= 0.5
)
4. 半对数坐标
y轴将以指数方式递增,基于半对数坐标绘制第二个子图,表示曲线【1, 10, 100, 1000, 100, 10, 1】
from __future__ import unicode_literals
from matplotlib import pyplot as plt
plt. figure( 'semilogy' , facecolor= 'lightgray' )
y = [ 1 , 10 , 100 , 1000 , 100 , 10 , 1 ]
ax = plt. gca( )
ax. grid( which= 'major' , axis= 'both' , linewidth= 1 , linestyle= '-.' , color= 'red' , alpha= 0.5 )
plt. semilogy( y)
plt. show( )
5. 散点图
可以通过每个点的坐标
、颜色
、大小
、形状
表示不同的特征值。
身高 体重 性别 年龄段 种族 180 80 男 中年 亚洲 160 50 女 青年 美洲
from __future__ import unicode_literals
from matplotlib import pyplot as plt
plt. scatter(
x,
y,
marker= '' ,
s= 10 ,
color= '' ,
edgecolor= '' ,
facecolor= '' ,
zorder= ''
)
numpy.random提供了normal函数,用于产生符合正态分布的随机数
n = 100
x = np. random. normal( 172 , 20 , n)
y = np. random. normal( 60 , 10 , n)
from __future__ import unicode_literals
from matplotlib import pyplot as plt
import numpy as np
n = 300
x = np. random. normal( 172 , 20 , n)
y = np. random. normal( 60 , 10 , n)
plt. figure( 'Persons' , facecolor= 'lightgray' )
plt. title( 'Persons' )
plt. xlabel( 'Height' , fontsize= 16 )
plt. ylabel( 'Weight' , fontsize= 14 )
plt. grid( linestyle= ':' )
d = ( x - 172 ) ** 2 + ( y - 60 ) ** 2
plt. scatter( x, y, marker= 'o' , s= 70 ,
label= 'Persons' , c= d, cmap= 'jet' )
plt. legend( )
plt. show( )
(x - 172)**2
代表300个身高到期望值的差距(y - 60) ** 2
代表300个体重到期望值的差距取平方是为了避免出现负值,也可取绝对值 二者相加求得该个体距离标准身高体重的误差,值越小距离标准身高体重越近。 cmap
代表颜色映射,jet
代表颜色从蓝到红(值从小到大),拼接_n
代表反转,比如:jet_n
代表颜色从蓝到红(值从大到小)
6. 填充
from matplotlib import pyplot as plt
plt. fill_between(
x,
sin_x,
cos_x,
sinx_< cos_x,
color= '' ,
alpha= 0.2
)
案例:绘制两条曲线:sin_x = sin(x)
cos_x = cos(x/2) / 2
[0-8π]
from __future__ import unicode_literals
from matplotlib import pyplot as plt
import numpy as np
n = 1000
x = np. linspace( 0 , 8 * np. pi, n)
sinx = np. sin( x)
cosx = np. cos( x / 2 ) / 2
plt. figure( 'Fill' , facecolor= 'lightgray' )
plt. title( 'Fill' , fontsize= 20 )
plt. xlabel( 'x' , fontsize= 14 )
plt. ylabel( 'y' , fontsize= 14 )
plt. tick_params( labelsize= 10 )
plt. grid( linestyle= ':' )
plt. plot( x, sinx, c= 'dodgerblue' , label= 'sin(x)' )
plt. plot( x, cosx, c= 'orange' , label= 'cos(x)' )
plt. legend( )
plt. fill_between(
x,
sinx,
cosx,
sinx < cosx,
color= 'green' ,
alpha= 0.2
)
plt. fill_between(
x,
sinx,
cosx,
sinx > cosx,
color= 'pink' ,
alpha= 0.2
)
plt. show( )
7. 条形图(柱状图)
from matplotlib import pyplot as plt
plt. figure( 'Bar' , facecolor= 'lightgray' )
plt. bar(
x,
y,
width,
color,
label,
alpha= 0.2
)
案例:先以柱状图绘制近12个月苹果的销量,然后再绘制橘子的销量
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
apples = np. array(
[ 42 , 34 , 22 , 31 , 40 , 54 , 23 , 42 , 35 , 47 , 59 , 50 ]
)
oranges = np. array(
[ 20 , 31 , 34 , 29 , 42 , 50 , 37 , 29 , 39 , 41 , 30 , 22 ]
)
bar_width = 0.2
x_ = range ( 1 , 13 )
a_x = [ w- bar_width/ 2 for w in x_]
plt. figure( 'Bar' , facecolor= 'lightgray' )
plt. title( 'Fruit sale volume' )
plt. xlabel( 'Month' , fontsize= 14 )
plt. ylabel( 'Sale Volume' , fontsize= 14 )
plt. tick_params( labelsize= 10 )
plt. grid( axis= 'y' , linestyle= ':' )
plt. bar(
a_x,
apples,
width= bar_width,
color= 'red' ,
label= 'apple' ,
alpha= 0.2
)
"""
plt.text(
x, 显示位置的横坐标
y+5, 显示位置的纵坐标(显示位置高于柱子高度5个点)
'%s' % y, 显示文本值(字符型)
ha='center', 水平对齐方式
va='top' 垂直对齐方式
)
"""
for x, y in zip ( a_x, apples) :
plt. text( x, y+ 5 , '%s' % y, ha= 'center' , va= 'top' )
o_x = [ w+ bar_width/ 2 for w in x_]
plt. bar(
o_x,
oranges,
width= bar_width,
color= 'orange' ,
label= 'orange' ,
alpha= 0.2
)
for x, y in zip ( o_x, oranges) :
plt. text( x, y+ 5 , '%s' % y, ha= 'center' , va= 'top' )
plt. xticks( x_)
plt. legend( )
plt. show( )
8. 饼图
plt. pie(
values,
spaces,
labels,
colors,
'%d%%' ,
shadow= True ,
startangle= 90 ,
radius= 1 ,
)
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
labels = [ 'Python' , 'JavaScript' , 'C++' , 'Java' , 'PHP' ]
values = [ 26 , 17 , 21 , 29 , 11 ]
spaces = [ 0.05 , 0.01 , 0.01 , 0.01 , 0.01 ]
colors = [ 'dodgerblue' , 'orangered' , 'limegreen' , 'violet' , 'gold' ]
plt. figure( 'pie' , facecolor= 'lightgray' )
plt. title( 'Pie' , fontsize= 20 )
plt. pie(
x= values,
explode= spaces,
labels= labels,
colors= colors,
autopct= '%.2f%%' ,
shadow= True ,
startangle= 0 ,
radius= 0.7 ,
)
plt. axis( 'equal' )
plt. legend( loc= 0 )
plt. show( )
9. 等高线图
组成等高线需要网络点坐标矩阵,也要每个点的高度,所以等高线属于3D数学模型范畴 绘制等高线的相关API
cntr = plt. contour(
x,
y,
z,
8 ,
colors= 'black' ,
linewidths= 0.5 ,
)
plt. clabel( cntr, inline_spacing= 1 , fmt= '%.2f' , fontsize= 10 )
plt. contourf( x, y, z, 8 , cmap= 'jet' )
"""
x:
0 1 2 3
0 1 2 3
0 1 2 3
0 1 2 3
y:
0 0 0 0
1 1 1 1
2 2 2 2
3 3 3 3
z:
9 3 5 2
7 9 4 2
8 3 7 4
5 9 7 8
"""
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
"""
例如 n = 5
[[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]
[-3. -1.5 0. 1.5 3. ]]
"""
n = 500
x, y = np. meshgrid( np. linspace( - 3 , 3 , n) ,
np. linspace( - 3 , 3 , n) )
z = ( 1 - x / 2 + x ** 5 + y ** 3 ) * np. exp( - x ** 2 - y ** 2 )
plt. figure( 'Contour' , facecolor= 'lightgray' )
plt. title( 'Contour' , fontsize= 18 )
plt. grid( linestyle= ':' )
cntr = plt. contour(
x,
y,
z,
8 ,
colors= 'black' ,
linewidths= 0.5 ,
)
plt. clabel( cntr, inline_spacing= 1 , fmt= '%.2f' , fontsize= 10 )
"""
inline_spacing 线条上数字与线条的距离
"""
plt. contourf( x, y, z, 8 , cmap= 'jet' )
plt. show( )
10. 热成像图
1 2 3
4 5 6
7 8 9
"""
upper: 缺省值,原点在左上方
lower: 原点在左下角
"""
plt. imshow( z, cmap= 'jet' , origin= 'lower' )
plt. colorbar( )
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
n = 500
x, y = np. meshgrid( np. linspace( - 3 , 3 , n) ,
np. linspace( - 3 , 3 , n) )
z = ( 1 - x / 2 + x ** 5 + y ** 3 ) * np. exp( - x ** 2 - y ** 2 )
plt. figure( 'Imshow' , facecolor= 'lightgray' )
plt. title( 'Imshow' , fontsize= 18 )
plt. grid( linestyle= ':' )
plt. imshow( z, cmap= 'jet' )
plt. colorbar( )
plt. show( )
11. 极坐标系
与笛卡尔坐标系不同,某些情况下极坐标系更适合显示与角度有关的图像,例如:雷达等。极坐标系可以描述极径
ρ
\rho
ρ 与极角
θ
\theta
θ 的线性关系
plt. figure( 'Polar' , facecolor= 'lightgray' )
plt. gca( projection= 'polar' )
plt. title( 'Polar' , fontsize= 20 )
plt. xlabel( r'$\rho$' , fontsize= 14 )
plt. ylabel( r'$\theta$' , fontsize= 14 )
plt. tick_params( labelsize= 10 )
plt. grid( linestyle= ':' )
plt. show( )
t = np. linspace( 0 , 4 * np. pi, 1000 )
r = 0.8 * t
plt. plot( t, r)
plt. show( )
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
plt. figure( 'Polar' , facecolor= 'lightgray' )
plt. gca( projection= 'polar' )
plt. title( 'Polar' , fontsize= 20 )
plt. xlabel( r'$\rho$' , fontsize= 14 )
plt. ylabel( r'$\theta$' , fontsize= 14 )
plt. tick_params( labelsize= 10 )
plt. grid( linestyle= ':' )
t = np. linspace( 0 , 4 * np. pi, 1000 )
r = 0.8 * t
plt. plot( t, r)
plt. show( )
我们可以看出,随着极角的增大,极径在变长 案例:在极坐标系中绘制正弦函数。y = 3sin(6x)
x = np. linspace( 0 , 6 ** np. pi, 1000 )
y = 3 * np. sin( 6 * x)
plt. shpw( )
12. 三维曲面(3D图像绘制)
matplotlib支持绘制三维曲面,若希望绘制三维曲面,需要使用axes3d
提供的3d坐标
from mpl_toolkits. mplot3d import axes3d
ax3d = plt. gca( projection= '3d' )
matplotlib支持绘制三维点阵、三维曲面、三维线框图
ax3d. scatter( . . )
ax3d. plot_surface( . . )
ax3d. plot_wireframe( . . )
ax3d. scatter(
x,
y,
marker,
s,
zorder,
color,
edgecolor,
facecolor,
c= v,
cmap= ''
)
案例:随机生成三组坐标,成标准状态分布规则,并且绘制他们
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
n = 500
x = np. random. normal( 0 , 1 , n)
y = np. random. normal( 0 , 1 , n)
z = np. random. normal( 0 , 1 , n)
plt. figure( '3D Scatter' , facecolor= 'lightgray' )
ax3d = plt. gca( projection= '3d' )
ax3d. set_xlabel( 'x' , fontsize= 16 )
ax3d. set_ylabel( 'y' , fontsize= 16 )
ax3d. set_zlabel( 'z' , fontsize= 16 )
d = x** 2 + y** 2 + z** 2
ax3d. scatter( x, y, z, marker= 'o' , s= 70 ,
c= d, alpha= 0.5 , cmap= 'jet' )
plt. tight_layout( )
plt. show( )
ax3d. plot_surface(
x,
y,
z,
rstride,
cstride,
cmap= 'jet'
)
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
n = 500
x, y = np. meshgrid( np. linspace( - 3 , 3 , n) ,
np. linspace( - 3 , 3 , n) )
z = ( 1 - x / 2 + x ** 5 + y ** 3 ) * np. exp( - x ** 2 - y ** 2 )
plt. figure( '3D Scatter' , facecolor= 'lightgray' )
plt. title( '3D Scatter' , fontsize= 18 )
ax3d = plt. gca( projection= '3d' )
ax3d. set_xlabel( 'x' , fontsize= 16 )
ax3d. set_ylabel( 'y' , fontsize= 16 )
ax3d. set_zlabel( 'z' , fontsize= 16 )
ax3d. plot_surface( x, y, z, rstride= 30 , cstride= 30 , cmap= 'jet' )
plt. tight_layout( )
plt. show( )
ax3d. plot_wireframe(
x,
y,
z,
rstride,
cstride,
linewidth= 1 ,
color= 'dodgerblue'
)
from __future__ import unicode_literals
import numpy as np
from matplotlib import pyplot as plt
n = 500
x, y = np. meshgrid( np. linspace( - 3 , 3 , n) ,
np. linspace( - 3 , 3 , n) )
z = ( 1 - x / 2 + x ** 5 + y ** 3 ) * np. exp( - x ** 2 - y ** 2 )
plt. figure( '3D Scatter' , facecolor= 'lightgray' )
plt. title( '3D Scatter' , fontsize= 18 )
ax3d = plt. gca( projection= '3d' )
ax3d. set_xlabel( 'x' , fontsize= 16 )
ax3d. set_ylabel( 'y' , fontsize= 16 )
ax3d. set_zlabel( 'z' , fontsize= 16 )
ax3d. plot_wireframe(
x,
y,
z,
rstride= 10 ,
cstride= 10 ,
linewidth= 1 ,
color= 'dodgerblue'
)
plt. tight_layout( )
plt. show( )
13. 简单动画
动画即在一段时间内快速连续的绘制图像 matplotlib提供了方法用于处理简单的动画绘制。定义update函数用于及时更新图像
from matplotlib import pyplot as plt
from matplotlib import animation as ma
def update ( number) :
pass
anim = ma. FuncAnimation( plt. gcf( ) , update, interval= 10 )
plt. show( )
案例:随机生成100个各种颜色的气泡,让其不断增大
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation as ma
n = 100
balls = np. zeros( n, dtype= [
( 'position' , float , 2 ) ,
( 'size' , float , 1 ) ,
( 'growth' , float , 1 ) ,
( 'color' , float , 4 )
]
)
"""
# 每组样本数据如下
# 位置 大小 生长速度 颜色
([0., 0.], 0., 0., [0., 0., 0., 0.])
"""
balls[ 'position' ] = np. random. uniform( 0 , 1 , ( n, 2 ) )
balls[ 'size' ] = np. random. uniform( 40 , 50 , n)
balls[ 'growth' ] = np. random. uniform( 10 , 20 , n)
balls[ 'color' ] = np. random. uniform( 0 , 1 , ( n, 4 ) )
plt. figure( 'Bubble' , facecolor= 'lightgray' )
plt. title( 'Bubble' , fontsize= 16 )
sc = plt. scatter( balls[ 'position' ] [ : , 0 ] ,
balls[ 'position' ] [ : , 1 ] ,
balls[ 'size' ] ,
color= balls[ 'color' ] )
def update ( number) :
balls[ 'size' ] += balls[ 'growth' ]
index = number % 100
balls[ 'size' ] [ index] = np. random. uniform( 40 , 50 , 1 )
balls[ 'position' ] [ index] = np. random. uniform( 0 , 1 , ( 1 , 2 ) )
sc. set_sizes( balls[ 'size' ] )
sc. set_offsets( balls[ 'position' ] )
anim = ma. FuncAnimation( plt. gcf( ) , update, interval= 30 )
plt. show( )
使用生成器函数提供数据,实现动画绘制 在很多情况下,绘制动画的参数是随机获取的,matplotlib支持定义generator生成器函数,用于生成数据,吧生成的数据交给update函数更新图像。
from matplotlib import animation as ma
def update ( data) :
t, v= data
. . .
pass
def generator ( ) :
yield t, y
anim = ma. FuncAnimation( plt. gcf( ) , update, generator, interval= 10 )
案例:绘制信号曲线:y = sin(2 *
π
\pi
π * t) * exp(sin(0.2 *
π
\pi
π * t)), 数据通过生成器函数生成,在update函数中绘制曲线。
import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation as ma
plt. figure( 'Signal' , facecolor= 'lightgray' )
plt. title( 'Signal' , fontsize= 14 )
plt. xlim( 0 , 10 )
plt. ylim( - 3 , 3 )
plt. grid( linestyle= '--' , color= 'lightgray' , alpha= 0.5 )
pl = plt. plot( [ ] , [ ] , color= 'dodgerblue' , label= 'Signal' ) [ 0 ]
x = 0
def update ( data) :
t, v = data
x, y = pl. get_data( )
x = np. append( x, t)
y = np. append( y, v)
pl. set_data( x, y)
if ( x[ - 1 ] > 10 ) :
plt. xlim( x[ - 1 ] - 10 , x[ - 1 ] )
def y_generator ( ) :
global x
y = np. sin( 2 * np. pi * x) * np. exp( np. sin( 0.2 * np. pi * x) )
yield ( x, y)
x += 0.05
anim = ma. FuncAnimation( plt. gcf( ) , update, y_generator, interval= 20 )
plt. tight_layout( )
plt. show( )