以下代码将一些文本与颜色条的右边缘对齐:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
img = plt.imshow(data, cmap='viridis')
color_bar = plt.colorbar(img, orientation='vertical')
color_bar.set_label('Color Bar Label', rotation=270, labelpad=15)
color_bar_position = color_bar.ax.get_position()
color_bar_width = color_bar_position.width
plt.text(color_bar_position.x1 + color_bar_width,1.02,'Right-Aligned Text', ha='right', va='center', transform=color_bar.ax.transAxes)
plt.show()
如何编辑此文本,以便文本与颜色条标签的右边缘(由红线表示)对齐 - 即下图中最右边元素的右边缘?该图只是一个例子;我需要将其应用到一段更复杂的代码中,因此我需要能够提取该边缘的 x 方向图形坐标来指定文本位置。
由于服务器错误,我目前无法上传图片
如果您使用
annotate
而不是 text
,那么您可以指定相对于不同艺术家或轴或各种轴/图形坐标的 x 和 y 位置。请注意,在绘制图形之前,轴标签位置是未知的(请参阅我对另一个问题的回答),因此在这里我强制使用 draw_without_rendering
进行绘制,以便将注释与标签对齐:
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
img = plt.imshow(data, cmap='viridis')
color_bar = plt.colorbar(img, orientation='vertical')
color_bar.set_label('Color Bar Label', rotation=270, labelpad=15)
color_bar_label = color_bar.ax.yaxis.label
plt.gcf().draw_without_rendering()
plt.annotate('Right-Aligned Text', (1, 1.02),
xycoords=(color_bar_label, color_bar.ax),
ha='right', va='center')
plt.show()
如果您想将文本与最右边的艺术家对齐而不知道先验该艺术家是什么,您可以使用
get_tight_bbox
找到所有组合艺术家的范围。
import matplotlib.pyplot as plt
import numpy as np
data = np.random.rand(10, 10)
img = plt.imshow(data, cmap='viridis')
color_bar = plt.colorbar(img, orientation='vertical')
color_bar.set_label('Color Bar Label', rotation=270, labelpad=15)
fig_bbox = plt.gcf().get_tightbbox()
rightmost = fig_bbox.max[0] * 72 # Convert position in inches to points
plt.annotate('Right-Aligned Text', (rightmost, 1.02),
xycoords=('figure points', color_bar.ax),
ha='right', va='center')
plt.show()