【问题标题】:How can I get the coordinates of a Matplotlib patch and use it to add a new axis?如何获取 Matplotlib 补丁的坐标并使用它来添加新轴?
【发布时间】:2017-03-13 17:45:01
【问题描述】:

我使用fig = plt.figure() 和ax = fig.add_subplot(my_arguments) 创建了一个图形和轴。然后我使用matplotlib.patches 添加了一些补丁。我通过使用matplotlib.transforms.Affine2D() 在数据坐标中平移和旋转来转换每个补丁,然后通过将ax.transData() 添加到我的Affine2D 转换的末尾来将转换后的坐标转换为显示坐标。

这是代码的简化版本:

import matplotlib as mpl
import matplotlib.patches as patches
from matplotlib.transforms import Bbox

fig = plt.figure()
ax = fig.add_subplot(111)
# plot anything here
ax.plot(range(10), 'ro')
my_patches = []
# in my code there many patches and therefore the line
# below is actually a list comprehension for each one
my_patches.append(
    patches.Rectangle( (1, 2), 10, 20, transform=mpl.transforms.Affine2D() \
    .translate(1, 1) \
    .rotate_deg_around(1, 2, 35)
    + ax.transData, fill=False, color='blue')
    )
# now add a new axis using the coordinates of the patch
patch = my_patches[0]
# get the coords of the lower left corner of the patch
left, bottom = patch.get_xy()
# get its width and height
width, height = patch.get_width(), patch.get_height()
# create a Bbox instance using the coords of the patch
bbox = Bbox.from_bounds(left, bottom, width, height)
# transform from data coords to display coords
disp_coords = ax.transData.transform(bbox)
# transform from display coords to figure coords
fig_coords = fig.transFigure.inverted().transform(disp_coords)
# new axis
ax2 = fig.add_axes(Bbox(fig_coords))
# plot anything else here
ax2.plot(range(10), 'bo')

但是,附加轴并未添加到图形中与补丁的变换坐标相同的位置(尽管它们很接近)。我错过了什么吗?

【问题讨论】:

  • 通过查看代码,我不清楚您要实现什么。您希望最终结果是什么样的?为什么需要这些转换才能实现?

标签: python matplotlib transformation patch


【解决方案1】:

我不确定这段代码的目的是什么,所以这可能不是你想要的。但是为了使坐标区框出现在坐标 (1,2) 处,您可能应该先绘制画布,然后再使用从补丁获得的坐标。

...
fig.canvas.draw()
left, bottom = patch.get_xy()
...

【讨论】:

  • 感谢@ImportanceOfBeingErnest!这正是我的想法......虽然我忘记了补丁只有在渲染时才会变得生动。正如查理布朗所说,“我真是个笨蛋!!” ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-02-20
  • 1970-01-01
  • 2011-06-03
  • 2021-02-22
  • 2020-10-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多