将带注释的文本与颜色栏标签文本对齐

时间:2018-07-16 15:39:09

标签: python matplotlib

我想找到一种方法,使注释自动与颜色条的标签文本对齐。举个例子:

import matplotlib.pyplot as plt
import numpy as np

fig, ax = plt.subplots(figsize=(5,10))
data = np.arange(1000, 0, -10).reshape(10, 10)
im = ax.imshow(data, cmap='Blues')
clb = plt.colorbar(im, shrink=0.4)
clb.ax.annotate('text', xy=(1, -0.075), xycoords='axes fraction')

enter image description here

我希望“文字”的最后一个t与彩条标签中的1000的最后0在同一x坐标上。我可以通过在注释中调整xy参数来手动执行此操作,但是我必须对许多图形执行此操作,并且希望找到一种从某处自动获取参数的方法。

如何获得文本标签的最大x坐标并以注释在该坐标上结束的方式进行注释?有人可以指出我正确的方向吗?非常感谢!

1 个答案:

答案 0 :(得分:1)

由于标签是左对齐的,但是您想根据该标签的 end 对齐其他文本,因此我担心除了从绘制的图形中找出坐标外别无选择图并相应地放置标签。

import matplotlib.pyplot as plt
from matplotlib import transforms
import numpy as np

fig, ax = plt.subplots(figsize=(5,4))
data = np.arange(1000, 0, -10).reshape(10, 10)
im = ax.imshow(data, cmap='Blues')
cbar = plt.colorbar(im)


# draw figure first to be able to retrieve coordinates
fig.canvas.draw()
# get the bounding box of the last label
bbox = cbar.ax.get_yticklabels()[-1].get_window_extent()
# calculate pixels back to axes coords
labx,_ = cbar.ax.transAxes.inverted().transform([bbox.x1,0]) 
ax.annotate('text', xy=(labx, -0.075), xycoords=cbar.ax.transAxes,
                 ha = "right")

plt.show()

enter image description here

请注意,一旦您之后更改图形大小或以任何其他方式更改布局,此方法将失败。因此,它应该始终排在代码的最后。