1

How to rotate matplotlib.patches.Polygon? The output from the code below shows nothing.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
fig, ax = plt.subplots(figsize=(10,3))
x = [0.3,0.6,.5,.4]
y = [0.7,0.7,0.9,0.9]

trapezoid = patches.Polygon(xy=list(zip(x,y)), fill=False)

t_start = ax.transData
t = mpl.transforms.Affine2D().rotate_deg(-45)
t_end = t_start + t

trapezoid.set_transform(t_end)

print(repr(t_start))
print(repr(t_end))
ax.add_patch(trapezoid)

plt.show()
Mr. T
  • 11,960
  • 10
  • 32
  • 54
Elena Greg
  • 1,061
  • 1
  • 11
  • 26
  • Did you check out posts such as [Unable to rotate a matplotlib patch object about a specific point using rotate_around( )](https://stackoverflow.com/questions/15557608/unable-to-rotate-a-matplotlib-patch-object-about-a-specific-point-using-rotate-a) and [Matplotlib: rotating a patch](https://stackoverflow.com/questions/4285103/matplotlib-rotating-a-patch) – JohanC Jan 14 '21 at 08:33
  • I tried it. I edited the code in my question. What is wrong that the output does not show the rotated object? – Elena Greg Jan 14 '21 at 09:12

1 Answers1

1

When composing the tranformations, you must use t_end = t + t_start instead of t_start + t. The + operator is overloaded: a + b means to first apply a and then apply b. For affine transformations this means the matrix product B@A where A and B are the transformation matrices of a and b respectively. The matrix product is not commutative.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
import copy

fig, ax = plt.subplots(figsize=(10,3))
x = [0.3,0.6,.5,.4]
y = [0.7,0.7,0.9,0.9]

trapezoid = patches.Polygon(xy=list(zip(x,y)), fill=False)
ax.add_patch(copy.copy(trapezoid))

t_start = ax.transData
t = mpl.transforms.Affine2D().rotate_deg(-45)
t_end = t + t_start

trapezoid.set_transform(t_end)
ax.add_patch(trapezoid)

plt.show()

enter image description here

Stef
  • 28,728
  • 2
  • 24
  • 52