1

I created a figure and axis using fig = plt.figure() and ax = fig.add_subplot(my_arguments). Then I added a few patches using matplotlib.patches. I transformed each patch by using matplotlib.transforms.Affine2D() to translate and rotate in data coordinates and then convert the transformed coordinates in display coordinates by adding ax.transData() to the end of my Affine2D transformations.

This is a simplified version of the code:

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')

However, the additional axis is not added to the figure at the same position as the transformed coordinates of the patch (they're close, though). Am I missing something?

1
  • By looking at the code, it's not clear to me what you are trying to achieve. What do you want to final result to look like and why do you need those transformations to get there? Commented Mar 13, 2017 at 18:10

1 Answer 1

2

I'm uncertain about what the purpose of this code is, so this might not be what you want. But in order for the axes box to appear at coordinates (1,2), you should probably draw the canvas first before working with coordinates obtained from patches.

...
fig.canvas.draw()
left, bottom = patch.get_xy()
...
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @ImportanceOfBeingErnest! That's exactly what I had in mind... although I had forgotten that patches only come to life when rendered. As would Charlie Brown say, "I'm such a blockhead!!" ;)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.