备注
前往结尾 以下载完整示例代码。
transforms.offset_copy#
这展示了如何使用 transforms.offset_copy 来创建一个变换,该变换将绘图元素(如文本字符串)定位在相对于任何坐标系中给定位置的屏幕坐标(点或英寸)的指定偏移处。
每个艺术家(文本、Line2D等)在创建时都有一个可以设置的变换,例如通过相应的pyplot函数。默认情况下,这通常是Axes.transData变换,从数据单位到屏幕像素。我们可以使用`.offset_copy`函数来创建这个变换的修改副本,其中修改包括一个偏移量。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.transforms as mtransforms
xs = np.arange(7)
ys = xs**2
fig = plt.figure(figsize=(5, 10))
ax = plt.subplot(2, 1, 1)
# If we want the same offset for each text instance,
# we only need to make one transform. To get the
# transform argument to offset_copy, we need to make the Axes
# first; the subplot function above is one way to do this.
trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
x=0.05, y=0.10, units='inches')
for x, y in zip(xs, ys):
plt.plot(x, y, 'ro')
plt.text(x, y, '%d, %d' % (int(x), int(y)), transform=trans_offset)
# offset_copy works for polar plots also.
ax = plt.subplot(2, 1, 2, projection='polar')
trans_offset = mtransforms.offset_copy(ax.transData, fig=fig,
y=6, units='dots')
for x, y in zip(xs, ys):
plt.polar(x, y, 'ro')
plt.text(x, y, '%d, %d' % (int(x), int(y)),
transform=trans_offset,
horizontalalignment='center',
verticalalignment='bottom')
plt.show()