Skip to content

Matplotlib - 变换

Matplotlib - 理解变换(Transforms)和坐标系

Section titled “Matplotlib - 理解变换(Transforms)和坐标系”

Matplotlib 使用一套变换(transformation)框架来将坐标从一个系统映射到另一个系统。这对于无论在缩放、平移或调整大小时,都能准确放置文本、注释或形状等元素至关重要。

理解这些坐标系有助于精确控制元素的放置。

你将主要遇到以下四种坐标系:

坐标系变换对象描述
数据坐标ax.transData这是绘制数据的坐标系。它是大多数绘图函数(如 ax.plot、ax.scatter)以及 ax.text 和 ax.annotate 的默认坐标系。其范围由 ax.set_xlim() 和 ax.set_ylim() 控制。位置随缩放/平移而改变。
Axes 坐标ax.transAxes这是 Axes 实例自身的坐标系,相对于其边界框。(0,0) 是 Axes 的左下角,(1,1) 是右上角。这与数据范围无关,非常适合在绘图区域内固定位置放置文本或元素(例如,始终在左上角)。
Figure 坐标fig.transFigure这是 Figure 实例的坐标系。(0,0) 是整个 Figure 画布的左下角,(1,1) 是右上角。这对于放置相对于整个图形的元素非常有用,例如图形标题 (fig.suptitle) 或特定 Axes 外部的文本。
显示坐标None 或 IdentityTransform()这是输出设备(屏幕、图像文件)的原始像素坐标系。(0,0) 是左下角像素,(width, height)(以像素为单位)是右上角像素。它很少直接用于绘图,但却是其他系统的基础。

许多涉及定位的 Matplotlib 函数(如 ax.text、ax.annotate、形状补丁等)接受一个 transform 关键字参数。通过设置这个参数,你可以指定提供的 x 和 y 值属于哪个坐标系。

示例:在不同坐标系中放置文本

Section titled “示例:在不同坐标系中放置文本”
import matplotlib.pyplot as plt
import numpy as np
fig, ax = plt.subplots(figsize=(7, 5))
# Some dummy data
ax.plot([1, 2, 3, 4], [1, 4, 2, 3])
ax.set_xlim(0, 5)
ax.set_ylim(0, 5)
ax.set_title('Transform Examples')
# 1. Text in Data Coordinates (Default for ax.text)
ax.text(2, 3, 'Data Coords (2, 3)', color='blue')
# 2. Text in Axes Coordinates (Fixed position within the Axes)
ax.text(0.05, 0.95, 'Axes Coords (0.05, 0.95)\nTop-Left Corner',
transform=ax.transAxes,
fontsize=10, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
ax.text(0.5, 0.5, 'Axes Coords (0.5, 0.5)\nCenter',
transform=ax.transAxes,
fontsize=10, horizontalalignment='center', verticalalignment='center',
bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.5))
# 3. Text in Figure Coordinates (Relative to the whole figure window)
fig.text(0.98, 0.02, 'Figure Coords (0.98, 0.02)\nBottom-Right Corner',
transform=fig.transFigure,
fontsize=10, horizontalalignment='right', verticalalignment='bottom',
bbox=dict(boxstyle='round', facecolor='lightgrey', alpha=0.5))
plt.show()

在此示例中:

  • 蓝色文本放置在数据坐标系中的 (x=2, y=3) 位置。如果你放大,它相对于数据的位置将保持固定,但其像素位置会改变。
  • 麦色文本使用 ax.transAxes 放置在 Axes 的左上角附近。即使你平移或缩放数据,它也会保持在左上角。
  • 浅蓝色文本使用 ax.transAxes 精确放置在 Axes 的中心位置。
  • 灰色文本使用 fig.transFigure 放置在 Figure 窗口的右下角附近。它的位置独立于 Axes。

理解并利用这些变换,可以有力地控制图形的标注和精确布局。