首页 > 解决方案 > 如何将 mpl_toolkits 的“AnchoredSizeBar”定位在其给定轴之外

问题描述

在将 AnchoredSizeBar 放置在其给定轴之外时,我面临着严重的困难。从 AnchoredSizeBar 参考中,loc 属性仅接受与用于创建 AnchoredSizeBar 的给定轴相关的“字符串”方法。

因此,如果我想将 AnchoredSizeBar 位置设置在给定轴之外,则 loc 属性将不起作用。事实上,它会引发错误消息。

有人知道绕过这个问题的方法吗?

如果可能的话,我想创建一个 AnchoredSizeBar,它的条形大小仍然相对于图中的给定轴,但是 AnchoredSizeBar 的位置可以放置在图实例内的任何位置。

这是我想要的代码片段:

import matplotlib.pyplot as plt


from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar


fig, ax = plt.subplots(figsize=(3, 3))

x_position = 0.15
y_position = 0.35

Figure_location = (x_position, y_position)    # figure xy locations relative to fig.transFigure.

axes_width_to_size_bar = 0.3

bar0 = AnchoredSizeBar(ax.transData, axes_width_to_size_bar, 'unfilled', loc=Figure_location, frameon=False, size_vertical=0.05, fill_bar=False)

ax.add_artist(bar0)


bar0_extent = bar0.get_extent()

fig.show()

我感谢你的时间。您忠诚的,

菲利普·里斯卡拉·里尔

标签: python-3.xmatplotlib

解决方案


AnchoredSizeBar子类matplotlib.offsetbox.AnchoredOffsetbox。额外的参数因此被传递给AnchoredOffsetbox. 这提供了参数bbox_to_anchorbbox_transform. 这些与图例相同,因此有关解释,请参见任何图例示例,例如How to put the legend out of the plot

比如把AnchoredSizeBar放在图的右上角,

import matplotlib.pyplot as plt

def draw_sizebar(ax):
    from mpl_toolkits.axes_grid1.anchored_artists import AnchoredSizeBar
    from matplotlib.transforms import Bbox
    asb = AnchoredSizeBar(ax.transData,
                          0.1,
                          "5 warp units",
                          loc='upper right',
                          pad=0.1, borderpad=0.5, sep=5,
                          frameon=False,
                          bbox_to_anchor=Bbox.from_bounds(0, 0, 1, 1),
                          bbox_transform=ax.figure.transFigure)
    ax.add_artist(asb)


fig, ax = plt.subplots()
draw_sizebar(ax)

plt.show()

在此处输入图像描述


推荐阅读