Matplotlib 笔记

>>> 官方文档 <<<

1
2
import matplotlib.pyplot as plt
import numpy as np

matplotlib anatomy

简单创建图象

1
2
3
4
5
6
7
8
fig = plt.figure(figsize=(1,1))  # 创建一个图,并指定长宽(1inch = 80px)
ax = fig.add_subplot(2, 3, 3) # 增加一个axes,位于2行3列网格的第三个位置(右上)
line, = ax.plot([1, 2, 3, 4], [1, 4, 2, 3], label='my label', color='blue') # 传入 自变量 与 因变量 以及 标签

fig.title_layout() # 简单修复一些显示不全的问题

fig.savefig('filename.format') # 保存图
fig.show() # 显示图
  1. 一张 figure 可以有很多 axes
  2. axes 即为图象部分
  3. 一个 axes 有两个 axies(座标轴)
  • 通过 fig.axes 属性获取已创建 axes
  • 通过 ax.lines 属性获取已创建 lines
  • 删除 axes 用delaxes方法
  • 增加共用 x 轴的 y 轴,用ax.twinx 方法
    • ax_same_x._get_lines.prop_cycler = ax._get_lines.prop_cycler 解决颜色重合
    • ax_another_same_x.spines['right'].set_position(('axes', 1.1)) 将更多的 y 轴右移以防重合

标识

  1. 轴名

    1
    2
    ax.set_xlabel('my xdata')
    ax.set_ylabel('my ydata')
  2. 标题

    1
    2
    ax.set_title('my axe title')
    fig.suptitle('my figure title')
  3. 网格

    1
    ax.grid(True)

Legend 图例

1
2
line.set_label('Label via method') # 设置图象的图例名
ax.legend(bbox_to_anchor=(1, 0, 1, 1), loc='upper left', ncol=2) # 生成图例,并指定位置

文档页

  • loc 指定位置
  • bbox_to_anchor 指定盒模型锚点及长宽 (x, y, width, height)
  • ncol 列数

交互模式

1
2
3
plt.ioff() # 关闭交互模式
with plt.ion():
# 开启交互模式的上下文