前言

本文的文字及图片来源于网络,仅供学习、交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以作处理。

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

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()

 

matplotlib库——5分钟入门,带你详细了解 Python 第1张

同一幅图中多条线

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库——5分钟入门,带你详细了解 Python 第2张

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()

 

都得到以下图形

matplotlib库——5分钟入门,带你详细了解 Python 第3张

多个子图

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()

 

matplotlib库——5分钟入门,带你详细了解 Python 第4张
# 设置图的位置、大小
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库——5分钟入门,带你详细了解 Python 第5张

对象关系

在 matplotlib 中,整个图像为一个 Figure 对象。在 Figure 对象中可以包含一个,或者多个 Axes 对象,每个 Axes 对象都是一个拥有自己坐标系统的绘图区域。

Title——标题
Axis——坐标轴
Label——坐标轴标注
Tick——刻度线
Tick Label——刻度注释
matplotlib库——5分钟入门,带你详细了解 Python 第6张

设置样式

设置图形样式时可参考以下表

axes.plot(x, y, color='red', linestyle='solid', marker='o')

颜色

 

matplotlib库——5分钟入门,带你详细了解 Python 第7张

简写形式

 

matplotlib库——5分钟入门,带你详细了解 Python 第8张

线类型

 

matplotlib库——5分钟入门,带你详细了解 Python 第9张

点标记

只列出了常用的(只支持简写形式)

matplotlib库——5分钟入门,带你详细了解 Python 第10张

图例

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'))

 

 

matplotlib库——5分钟入门,带你详细了解 Python 第11张

调整坐标轴的上下限

# 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)

 

直至坐标轴显示间隔

from matplotlib.ticker import MultipleLocator
# 如设置主要刻度线间隔为 2
axes.xaxis.set_major_locator(MultipleLocator(2))

 

调整坐标轴标签的显示

# 当点比较密集时,x 轴刻度线标签可能会重叠在一起,尤其是时间时
# 1. 对于时间可以使用 autofmt_xdate 自动调整对齐和旋转
fig.autofmt_xdate()
# 2. 通用的
ax.set_xticklabels(xticks, rotation=30, ha='right')

# 对于日期显示还可以自定义格式
from matplotlib.dates import DateFormatter
ax.xaxis.set_major_formatter(DateFormatter('%Y-%m'))

 

设置坐标轴名称

# 坐标轴下方或左边显示的标签
ax.set_xlabel('Time Series')
ax.set_ylabel('Microseismicity')

 

综合示例

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()

 

matplotlib库——5分钟入门,带你详细了解 Python 第12张

一些配置项

# 使用 pycharm 运行 plt.show() 默认不在独立窗口显示(terminal 运行可以)
# 切换 backend 为 TkAgg 时, pycharm 运行可以在独立窗口展示图,同时 terminal 运行也可以
# 默认 non-interactive backends = agg
# 如果不切换 backend 又想在独立窗口显示,可以按如下设置
# File -> Settings -> Tools -> Python Scientific -> 去掉Show plots in tool window勾选
plt.switch_backend('TkAgg')

# 当 figure 开启超过 20 个时会有警告(一般循环画图出现),可以主动 close 图
for y in data:
    fig: plt.Figure = plt.figure()
    axes = fig.add_subplot()
    axes.plot(y, color='red', marker='o', linestyle='solid')
    plt.savefig('xxx.png')
    plt.close()


# 设置网格线
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

 

matplotlib库——5分钟入门,带你详细了解 Python 第13张

图形类型

 

matplotlib库——5分钟入门,带你详细了解 Python 第14张 matplotlib库——5分钟入门,带你详细了解 Python 第15张 matplotlib库——5分钟入门,带你详细了解 Python 第16张

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄