
Matplotlib 是一个 Python 的 2D绘图库(当然也可以画三维形式的图形哦),它以各种硬拷贝格式和跨平台的交互式环境生成出版质量级别的图形 。通过 Matplotlib,开发者可以仅需要几行代码,便可以生成绘图,直方图,功率谱,条形图,错误图,散点图等。
Matplotlib 主要有两大模块:pyplot
和 pylab
,这二者之间有何区别和联系呢?
首先 pyplot
和 pylab
都可以画出图形,且两者 API 也是类似的, 其中 pylab
包括了许多 numpy
和 pyplot
模块中常用的函数,对交互式使用(如在 IPython 交互式环境中)来说比较方便,既可以画图又可以进行计算,不过官方推荐对于项目编程最好还是分别导入 pyplot
和 numpy
来作图和计算。
先来个简单的
import numpy as np
from matplotlib import pyplot as plt
x = np.arange(0, 11)
y = 2*x
plt.plot(x, y, marker='o')
plt.show()

同一幅图中多条线
x = np.arange(0, 11)
y1 = 2*x
y2 = 4*x
# g-- 表示绿色虚线 r- 表示红色实线
plt.plot(x, y1, 'g--')
plt.plot(x, y2, 'r-')
plt.show()

Matplotlib Api 风格
Matplotlib 有两种编程风格,一种是 Matlab 用户熟悉的风格,一种中面向对象式的风格,推荐后者
Matlab 风格的 Api
plt.figure(figsize=(10, 5))
x = [1, 2, 3]
y = [2, 4, 6]
plt.plot(x, y, 'r')
plt.xlabel('x axis')
plt.ylabel('y axis')
plt.title('figure title')
plt.show()
面向对象风格的 Api
fig = plt.figure(figsize=(10, 5))
# add_subplot(nrows, ncols, index, **kwargs) 默认 (1, 1, 1)
axes = fig.add_subplot()
x = [1, 2, 3]
y = [2, 4, 6]
axes.plot(x, y, 'r')
axes.set_xlabel('x axis')
axes.set_ylabel('y axis')
axes.set_title('figure title')
plt.show()
都得到以下图形

多个子图
fig: plt.Figure = plt.figure(figsize=(10, 5))
axes1 = fig.add_subplot(2, 1, 1) # (nrows, ncols, index)
# 与 axes1 共享x,y轴
# the axis will have the same limits, ticks, and scale as the axis
# facecolor: 坐标轴图形背景颜色
axes2 = fig.add_subplot(2, 1, 2, sharex=axes1, sharey=axes1, facecolor='k')
x = np.linspace(-5, 5, 100)
y1 = np.sin(x)
y2 = np.cos(x)
axes1.plot(x, y1, color='red', linestyle='solid')
axes2.plot(x, y2, color='#00ff00', linestyle='dashed')
axes1.set_title('axes1 title')
axes2.set_title('axes2 title')
plt.show()

# 设置图的位置、大小
axes1 = fig.add_axes([0.1, 0.1, 0.8, 0.8]) # [left, bottom, width, height]
axes2 = fig.add_axes([0.7, 0.7, 0.2, 0.2])

对象关系
在 matplotlib 中,整个图像为一个 Figure 对象。在 Figure 对象中可以包含一个,或者多个 Axes 对象,每个 Axes 对象都是一个拥有自己坐标系统的绘图区域。
Title——标题
Axis——坐标轴
Label——坐标轴标注
Tick——刻度线
Tick Label——刻度注释

设置样式
设置图形样式时可参考以下表
axes.plot(x, y, color='red', linestyle='solid', marker='o')
颜色
参数 | 说明 |
---|---|
color='blue' | 标准颜色名称 |
color='g' | 缩写颜色的代码(rgbcmyk) |
color='0.75' | 范围在0-1直间的灰度值 |
color='#ff99dd' | 十六进制 |
color=(1.0,0.2,0.3) | RGB元组,范围(0,1) |
简写形式
白色 | |||||||
---|---|---|---|---|---|---|---|
r | g | b | c | m | y | k | w |
线类型
参数 | 简写形式 | 说明 |
---|---|---|
linestyle='solid' | - | 实线 |
linestyle='dashed' | -- | 虚线 |
linestyle='dashdot' | -. | 点划线 |
linestyle='dotted' | : | 点线 |
点标记
只列出了常用的(只支持简写形式)
参数 | 简写形式 | 说明 |
---|---|---|
marker='' | . | 点 |
marker='' | , | 像素 |
marker='' | o | 圆 |
marker='' | s | 方形 |
marker='' | ^ | 三角形 |
marker='' | $★$ | 展示原始字符(用两个$符包裹字符) |
图例
axes.plot(x, y, 'r', label='y=2x')
# or
axes.set_label('y=2x')
axes.legend(loc='upper right') # 默认 legend(loc='best')
# 同时设置多个
plt.legend((axes1, axes2, axes3), ('label1', 'label2', 'label3'))
Location String | Location Code |
---|---|
'best' | 0 |
'upper right' | 1 |
'upper left' | 2 |
'lower left' | 3 |
'lower right' | 4 |
'right' | 5 |
'center left' | 6 |
'center right' | 7 |
'lower center' | 8 |
'upper center' | 9 |
'center' | 10 |
调整坐标轴的上下限
# xlim(left=None, right=None, emit=True, auto=False, *, xmin=None, xmax=None)
# ylim(bottom=None, top=None, emit=True, auto=False, *, ymin=None, ymax=None)
axes.set_xlim(0, 8)
axes.set_ylim(0, 8)
综合示例
fig = plt.figure()
axes = fig.add_subplot()
t = np.linspace(0, np.pi, 64)
x = np.sin(t)
y = np.cos(t) + np.power(x, 2.0 / 3)
# 采用参数定义样式
axes.plot(x, y, color='red', marker='o', linestyle='solid', linewidth=2, label='x>0')
# 采用简写 color marker linestyle 没有顺序之分,不需要都写
axes.plot(-x, y, 'ro-', linewidth=2, label='x<0')
# 设置标题
axes.set_title('心型图', fontdict={'size': 16, 'color': 'r', 'family': 'SimHei'})
# 设置坐标轴数值范围
axes.set_xlim(-1.5, 1.5)
# 设置坐标轴刻度线
axes.set_xticks([-1.5, -1, 0, 1, 1.5])
# 设置坐标轴刻度线标签,不设置则是坐标轴数值
axes.set_xticklabels(['-1.5', '-1', '原点', '1', '1.5'], fontdict={'family': 'SimHei'})
# 设置显示图例
axes.legend()
# 设置显示网格线
axes.grid(color='#cccccc', ls='-.', lw=0.25)
plt.show()

一些配置项
# 使用 pycharm 运行 plt.show() 默认不在独立窗口显示(terminal 运行可以)
# 切换 backend 为 TkAgg 时, pycharm 运行可以在独立窗口展示图,同时 terminal 运行也可以
# 默认 non-interactive backends = agg
plt.switch_backend('TkAgg')
# 设置网格线
plt.grid(True)
# 设置字体,默认不支持中文显示,可以指定中文字体来显示中文
plt.rcParams["font.family"] = 'SimHei' # mac os可以使用 Heiti TC
# 也可以在使用的时候分别设置
axes.set_title('中文字体 SimHei', fontdict={'size': 16, 'color': 'r', 'family': 'SimHei'})
# 解决坐标轴负数的负号显示问题
plt.rcParams['axes.unicode_minus'] = False

图形类型
使用方法1 | 使用方法2 | 类型 |
---|---|---|
plt.plot | axes.plot | 折线图 |
plt.scatter | axes.scatter | 散点图 |
plt.bar | axes.bar | 柱状图 |
plt.hist | axes.hist | 直方图 |
plt.pie | axes.pie | 饼图 |


网友评论