0

EDIT: The question was not duplicate, but about a subtlety in the argument, that isn't mentioned in the answers.

Trying to rotate rectangles in Matplotlib, I added transform argument, but whatever its value is, the rectangle is simply broken.

Here's the code and outputs:

    import matplotlib
    %matplotlib inline

    import matplotlib.pyplot as plt
    from matplotlib.patches import Rectangle

    fig, ax = plt.subplots(1, 1, figsize=(20, 10))
    ax.set_xlim(0, 20)
    ax.set_ylim(0, 20)
    plt.axis('off')

    ax.add_patch(Rectangle(
            (5, 5), 2, 2,
            color='#444444', ec='#444444', capstyle='round',
            linewidth=20, linestyle='-',
        joinstyle='round',
        #transform=None
    ))

Output:

Rectangle as intended

Now I try to rotate it. Here are 3 ways, all produce the same output image.

#1 add trasform=None to Rectangle parameters. #2 add transform=matplotlib.transforms.Affine2D().rotate_deg_around(0, 0, 15) #3 as in another question:

    r = Rectangle(
            (5, 5), 2, 2,
            color='#444444', ec='#444444', capstyle='round',
            linewidth=20, linestyle='-',
        joinstyle='round',
    )

    t_start = ax.transData
    t = mpl.transforms.Affine2D().rotate_deg(-1)

    r.set_transform(t)
    ax.add_patch(r)

The output is the same in all cases:

Rectangle still broken

What am I doing wrong?

Matplotlib version is 3.4.2.

culebrón
  • 34,265
  • 20
  • 72
  • 110
  • 1
    Did you carefully read the second answer of [Matplotlib: rotating a patch](https://stackoverflow.com/questions/4285103/matplotlib-rotating-a-patch)? Did you notice you need to add `+ ax.transData`? Note that there are many many similar questions on stackoverflow. Did you notice that in your last example you defined `t_start` but don't use it? – JohanC Jun 22 '21 at 15:49
  • @JohanC yes, I did read it, but it does not say explicitly how trasforms work. I needed 15 minutes of trial and error to figure it out myself. – culebrón Jun 22 '21 at 15:51
  • 1
    Well, there is a [tutorial](https://matplotlib.org/stable/tutorials/advanced/transforms_tutorial.html) – JohanC Jun 22 '21 at 15:52
  • @JohanC Thansk. Well, my problem was just the tiny difference, that you need to pass it the old transformation and add the new one. ax.transData + new_transformation. This explains why `transformation=None` breaks it (I guess it turns the rectangle into a point). – culebrón Jun 22 '21 at 15:58

0 Answers0