matplot绘图主要的对象有pyplot,figure,axes三种对象。分别对应画布总体对象,画布和轴。
concept
- Figure Figure对象可以包含一个或者多个Axes
- Axes 每个Axes对象都是一个拥有自己坐标系统的绘图区域
- Axis Axis为坐标轴,
- patches
pyplot
pyplot是matplot的基本绘图对象,pyplot是有状态的,因此,每次对pyplot的设置,都会被记录到它的状态中。
折线图
折线图一般使用plt.plot()函数进行绘制。
import matplotlib.pyplot as plt
import numpy as np
if __name__ == '__main__':
x = np.arange(0, 5, 0.2) # 输入数据
line = plt.plot(x, x, 'r--', x, x**2, 'bs', x, x**3, 'g^') # 在同一个图中画三条curve
plt.title("plot tutor") # 图的描述
plt.axis([0, 5, 0, 20]) # x轴和y轴的范围
plt.xlabel("order of numbers") # x轴的描述
plt.ylabel("numbers") # y轴的描述
plt.show()
pass
直方图
直方图可以使用plt.hist() 进行画图,代码及效果如下:
def plot_hist():
mu, sigma = 100, 15
x = mu + sigma * np.random.randn(10000)
# the histogram of the data
n, bins, patches = plt.hist(x, 50, normed=1, facecolor='b', alpha=0.75)
plt.xlabel('Smart')
plt.ylabel('Probability')
plt.title('Histogram of IQ')
plt.text(60, .025, r'$\mu=100, \ \sigma=15$') # 信息标注
plt.axis([40, 160, 0, 0.03])
plt.grid(True) # 是否显示网格
plt.annotate('max y', xy=(100, 0.025), xytext=(120, 0.028),
arrowprops=dict(facecolor='black', shrink=0.05),)
对应的参数如下:
- x : (n,) 数组
- bins : integer or array_like, 箱数
- range : tuple, optional,(x.min(), x.max()) default: None 最大最小值
- normed : boolean, optional, default: False 符合正态分布
- weights : array_like, shape (n, ), optional, 权重,与x数组相同
- cumulative : boolean, optional, default 是否累加
- bottom : array_like, scalar, or None, default: None,默认为0,底部为0
- histtype : [‘bar’ | ‘barstacked’ | ‘step’ | ‘stepfilled’], 直方图的类型
1.‘bar’ 条状图- ‘barstacked’
- step 波浪状图
- stepfilled 填充的波浪状图
- align : [‘left’ | ‘mid’ | ‘right’], optional, default: ‘mid’ 对齐
- ‘left’: 与数字左对齐.
- ‘mid’: 中间对齐.
- ‘right’: 右对齐.
- orientation : [‘horizontal’ | ‘vertical’], optional,默认垂直
- rwidth : scalar, optional, default: None 默认计算bar的宽度
- log : boolean, optional, default log形式
- color : color or array_like of colors, optional, default: None 颜色
- label : string, optional, default: 每个桶打上label?
- stacked : boolean, optional, default 多维数据使用
折线的属性
setp方法用于设置折线的属性,当然也可以直接在plt.plot中设置折现的属性。
plt.plot(x, y, linewidth=2.0)
# or
lines = plt.plot(x1, y1, x2, y2) #返回绘制的两条折现,也可以使用line1,line2对序列进行解包
# use keyword args
plt.setp(lines, color='r', linewidth=2.0) #设置折线的宽度
样式
matplot中自带了图标的样式,常用的图标样式例如R风格为”ggplot”,调用图表的风格可以使用如下代码:
import matplotlib.pyplot as plt
plt.style.use('ggplot')
查看已有的风格:
print plt.style.available
可以在matplot中的风格路径下,自定义自己的画图风格(命名+.mplstyle):
~/.matplotlib/stylelib/presentation.mplstyle
内部可定义如下分割:
axes.titlesize : 24
axes.labelsize : 20
lines.linewidth : 3
lines.markersize : 10
xtick.labelsize : 16
ytick.labelsize : 16
最后当然可以同时使用多个主题,但如果键值冲突的话,后引用的会覆盖前面的。
plt.style.use(['dark_background', 'presentation'])
线条
关于线条方面的设置,可以查看matplot线条帮助文档
颜色
在涉及文字的地方均可以设置字体和对应的颜色,颜色的key为color,其中颜色可以指定为如下几种形式
- 灰度等级
- 0.75 (0~1.0)
- 纯色
- b : blue
- g : green
- r : red
- 16进制颜色:
- #eeefff
RGB三元组颜色:
(0.0, 0.0, 0.0)
plt.xlabel(u"输入变量", fontsize=14, color='blue') # x轴的描述
透明度
透明度可以用key为alpha的字段指定,其值范围为0~1
信息标注
信息标注,可以实现图中填写各种各样的文字信息,信息标注可以引入latex中的数学表达式,功能非常强大。标注函数中的kwargs对应的配置可参考附录中的信息
标注x轴 xlabel()
函数原型为matplotlib.pyplot.xlabel(s, args, *kwargs),
对应的参数有如下:
- ‘fontsize’ : ‘small’,
- ‘verticalalignment’ : ‘top’,
- ‘horizontalalignment’ : ‘center’
标注y轴 ylabel()
函数原型为matplotlib.pyplot.ylabel(s, args, *kwargs)
- ‘fontsize’ : ‘small’,
- ‘verticalalignment’ : ‘center’,
- ‘horizontalalignment’ : ‘right’,
- ‘rotation’=’vertical’ :
标题 title()
函数原型为matplotlib.pyplot.title(s, args, *kwargs)
- s : str
- fontdict : dict
- ‘fontsize’
- “fontweight’ : rcParams[‘axes.titleweight’],
- ‘verticalalignment’: ‘baseline’,
- ‘horizontalalignment’: loc
- loc : {‘center’, ‘left’, ‘right’}
大标题 suptitle()
函数原型为matplotlib.pyplot.suptitle(args, *kwargs),几个默认参数如下:
- x : 0.5
- y : 0.98
- horizontalalignment : ‘center’
- verticalalignment : ‘top’
例:
fig.suptitle('bold figure suptitle', fontsize=14, fontweight='bold')
标注箭头 annotate()
annotate可以在图中标注一部分关键的点,并以箭头的方式指出。函数原型为matplotlib.pyplot.annotate(args, *kwargs),几个默认参数如下:
s : 标注文字
xy : (x, y) 指向的点坐标
xytext : (x, y) 文字的坐标点
xycoords : 点坐标的类型? default: “data” Examples: “figure points”, “figure pixels”, “figure fraction”, “axes points”,
textcoords : 文字坐标点的类型,Examples: “figure points”, “figure pixels”, “figure fraction”, “axes points”.
arrowprops : line2D,箭头线条的类型,常用方法:
arrowprops=dict(facecolor='black', shrink=0.05)
详细可参考文档
例:
ax.annotate('annotate', xy=(2, 1), xytext=(3, 4),
arrowprops=dict(facecolor='black', shrink=0.05))
标注任意位置text()
matplotlib.pyplot.text(x, y, s, fontdict=None, withdash=False, **kwargs)用于标注任意一个位置,参数意义如下:
- x,y: 标注的坐标位置
- s: 标注内容
- fontdict: 字体内容,一般定义在matplot中rcParams配置文件中
- fontsize
- fontweight
- verticalalignment:垂直对齐 “baseline”,”center”
- horizontalalignment: 水平对齐 “loc”, “center”
- withdash: 是否使用虚线框
- **kwargs:
- fontsize
text可以被一个矩形包裹,使用方法如下:
ax.text(3, 8, 'boxed italics text in data coords', style='italic',
bbox={'facecolor':'red', 'alpha':0.5, 'pad':10})
所有的图最后可以展示如下:
饼图
饼图可以使用plt.pie制作。运行下面代码可以得到一个饼图,饼图的
def plot_pie():
# The slices will be ordered and plotted counter-clockwise.
labels = 'Frogs', 'Hogs', 'Dogs', 'Logs'
sizes = [15, 30, 45, 10]
colors = ['yellowgreen', 'gold', 'lightskyblue', 'lightcoral']
plt.pie(sizes, labels=labels, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=90)
# 长宽比例相等,这样形成的图就是一个正圆
plt.axis('equal')
plt.suptitle(u"xx大厦", fontsize=14)
plt.show()
pie的相关参数如下:
- explode: 默认各个扇形不分离,若数组中的数大于0,则表示偏离
- colors: 每个色块的颜色
- labels: 每个色块的标签
- autopct: [ None | format string | format function ],每个色块的数值,可以是函数,也可以是格式化字符串。字符串使用%字符串格式,格式化字符串有些类似C语言的格式化字符串
- pctdistance: scalar,20%对应的距离色块中心的距离,默认为0.6
- labeldistance: scalar
- The radial distance at which the pie labels are drawn
- shadow: [ False | True ],是否有阴影
- startangle: [ None | Offset angle ] 色块的旋转
- radius: [ None | scalar ] 饼图的半径,默认为1
- counterclock: [ False | True ] 饼图显示比例的顺序
- wedgeprops: [ None | dict of key value pairs ]
- wedgeprops = { ‘linewidth’ : 3 } 用于设置wedge对象
- textprops: [ None | dict of key value pairs ] 文字对象
subplot
subplot是用于在绘图版上绘制多张图标的函数。
subplot, numrows(行数), numcols(列数),fignum(图数),
plt.figure(1)
plt.subplot(2, 1, 1)
plt.plot(t1, f(t1), 'bo', t2, f(t2), 'k')
plt.subplot(2, 1, 2)
plt.plot(t2, np.cos(2*np.pi*t2), 'r--')
plt.show()
附录
字体知识
- 在字体排印学里,衬线指的是字母结构笔画之外的装饰性笔画。有衬线的字体叫衬线体(serif);没有衬线的字体,则叫做无衬线体(sans-serif),无衬字体往往拥有相同的曲率,笔直的线条,锐利的转角。
中文支持
修改matplotlibrc配置文件,在文件中找到如下两行,添加微软雅黑并去掉二者面前的注释
#font.family : sans-serif #font.sans-serif : Microsoft Yahei,Bitstream Vera Sans, Lucida Grande, Verdana, Geneva, Lucid, Arial, Helvetica, Avant Garde, sans-serif
win10上没有自带ttf格式字体文件,可以到微软官网上下载
- 把下载的字体放到\Python27\Lib\site-packages\matplotlib\mpl-data\fonts\ttf中
- 删除.matplotlib\下的两个字体缓存文件,运行matplot程序后会自动刷新缓存
重新运行自己的程序如下图,有中文的地方需要使用u’中文’标识为unicode:
import matplotlib.pyplot as plt import numpy as np
if __name__ == '__main__':
x = np.arange(0, 5, 0.2) # 输入数据
line = plt.plot(x, x, 'r--', x, x**2, 'bs', x, x**3, 'g^') # 在同一个图中画三条curve
plt.title(r"plot tutor$\sigma_i=15$") # 图的描述
plt.axis([0, 5, 0, 20]) # x轴和y轴的范围
plt.xlim(0, 5) # x轴的范围
plt.ylim(0, 20) # y轴的范围
plt.xlabel(u"输入变量", fontsize=14, color='blue') # x轴的描述
plt.ylabel(u"输出变量", fontsize=14, color='blue') # y轴的描述
plt.legend(u"x = 小时, y = 个数")
plt.show()
text可用配置(kwargs)
- alpha 0.0~1.0 透明度,越小越透明
- animated [True | False]
- axes an Axes instance
- backgroundcolor 背景色
- bbox 矩形框
- clip_box a matplotlib.transforms.Bbox instance
- clip_on [True | False]
- clip_path [ (Path, Transform) | Patch | None ]
- color 字体颜色
- contains a callable function
- family 字体
- figure figure实例对象
- fontproperties or font_properties a matplotlib.font_manager.FontProperties instance
- gid an id string
- horizontalalignment or ha [ ‘center’ | ‘right’ | ‘left’ ] 水平对齐
- label string or anything printable with ‘%s’ conversion.
- linespacing 几倍行距float
- lod [True | False]
- multialignment [‘left’ | ‘right’ | ‘center’ ] 对齐
- path_effects unknown
- picker [None|float|boolean|callable]
- position (x,y)位置
- rasterized [True | False | None]
- rotation [ 旋转角度 | ‘vertical’ | ‘horizontal’ ]
- rotation_mode unknown
- size or fontsize [size in points | ‘xx-small’ | ‘x-small’ | ‘small’ | ‘medium’ | ‘large’ | ‘x-large’ | ‘xx-large’ ]字体大小
- sketch_params unknown
- snap unknown
- stretch or fontstretch [a numeric value in range 0-1000 | ‘ultra-condensed’ | ‘extra-condensed’ | ‘condensed’ | ‘semi-condensed’ | ‘normal’ | ‘semi-expanded’ | ‘expanded’ | ‘extra-expanded’ | ‘ultra-expanded’ ]
- style or fontstyle [ ‘normal’ | ‘italic’ | ‘oblique’]
- text string or anything printable with ‘%s’ conversion.
- transform Transform instance
- url a url string
- variant or fontvariant [ ‘normal’ | ‘small-caps’ ]
- verticalalignment or va or ma [ ‘center’ | ‘top’ | ‘bottom’ | ‘baseline’ ]
- visible [True | False] 是否可见
- weight or fontweight [a numeric value in range 0-1000 | ‘ultralight’ | ‘light’ | ‘normal’ | ‘regular’ | ‘book’ | ‘medium’ | ‘roman’ | ‘semibold’ | ‘demibold’ | ‘demi’ | ‘bold’ | ‘heavy’ | ‘extra bold’ | ‘black’ ]
- x float 位置
- y float 位置
- zorder 所在层序号