gpt4 book ai didi

python - 将注释文本与颜色条标签文本对齐

转载 作者:行者123 更新时间:2023-12-01 09:14:40 25 4
gpt4 key购买 nike

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

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 坐标并以注释在该坐标上结束的方式进行注释?有人能指出我正确的方向吗?非常感谢!

最佳答案

由于标签是左对齐的,但您想根据该标签的结束对齐附加文本,我担心除了从绘制的坐标中找出坐标之外别无选择计算并相应地放置标签。

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

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

关于python - 将注释文本与颜色条标签文本对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51365529/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com