在图的坐标系中设置轴标签而不是轴

时间:2015-07-10 16:36:48

标签: python matplotlib

我想使用图形的坐标系而不是轴来设置轴标签的坐标(或者如果这不可能至少是某些绝对坐标系)。

换句话说,我想在这两个例子的同一位置贴上标签:

import matplotlib.pyplot as plt
from pylab import axes

plt.figure().show()
ax = axes([.2, .1, .7, .8])
ax.plot([1, 2], [1, 2])
ax.set_ylabel('BlaBla')
ax.yaxis.set_label_coords(-.1, .5)
plt.draw()

plt.figure().show()
ax = axes([.2, .1, .4, .8])
ax.plot([1, 2], [1, 2])
ax.set_ylabel('BlaBla')
ax.yaxis.set_label_coords(-.1, .5)

plt.draw()
plt.show()

这在matplotlib中是否可行?

Illustrate difference

1 个答案:

答案 0 :(得分:2)

是。您可以使用变换从一个坐标系转换到另一个坐标系。这里有一个深入的解释:http://matplotlib.org/users/transforms_tutorial.html

如果您想使用图形坐标,首先您需要从图形坐标转换为显示坐标。你可以用fig.transFigure做到这一点。之后,当您准备好绘制轴时,可以使用ax.transAxes.inverted()从显示转换为轴。

import matplotlib.pyplot as plt
from pylab import axes

fig = plt.figure()
coords = fig.transFigure.transform((.1, .5))
ax = axes([.2, .1, .7, .8])
ax.plot([1, 2], [1, 2])
axcoords = ax.transAxes.inverted().transform(coords)
ax.set_ylabel('BlaBla')
ax.yaxis.set_label_coords(*axcoords)
plt.draw()

plt.figure().show()
coords = fig.transFigure.transform((.1, .5))
ax = axes([.2, .1, .4, .8])
ax.plot([1, 2], [1, 2])
ax.set_ylabel('BlaBla')
axcoords = ax.transAxes.inverted().transform(coords)
ax.yaxis.set_label_coords(*axcoords)

plt.draw()
plt.show()
相关问题