1

I want to apply different transformations to a patch, including rotating and changing the fill color. Hier is the piece of code already inspired by Matplotlib: rotating a patch

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
from matplotlib.collections import PatchCollection

fig = plt.figure()
ax = fig.add_subplot(111)

myAngles=[0, -45, -90]
myColors=[30, 40, 50]
myPatches=[]

for color, angle in zip (myColors,myAngles):
    #r2 = patches.Rectangle((0,0), 20, 40, color=color,  alpha=0.50)
    r2 = patches.Rectangle((0,0), 20, 40)
    t2 = mpl.transforms.Affine2D().rotate_deg(angle) + ax.transData
    r2.set_transform(t2)
    #ax.add_patch(r2)
    myPatches.append(r2)

    plt.xlim(-20, 60)
    plt.ylim(-20, 60)

    plt.grid(True)


collection = PatchCollection(myPatches, cmap=mpl.cm.jet, alpha=0.5)
collection.set_array(np.array(myColors))
ax.add_collection(collection)

plt.show()

Unfortunatly, the transformation is lost when I get out of the for loop. If I add the patch to the ax inside the loop, then everything is fine. But I have to do it at the end, because the colors are collected in the loop and should be applied later on.

Advices of any kind are highly appreciated

Cheers

Armel

Piccolo
  • 1,022
  • 2
  • 13
  • 15
  • Did you want the `xlim`,`ylim` and `grid` calls in the loop, or is this just an indentation error created by posting on SO? This has nothing to do with your specific question, but just thought I'd mention it. – Yann Sep 20 '11 at 12:52
  • It is indeed an indentation error! Thx for mentioning. – Piccolo Sep 20 '11 at 13:37

1 Answers1

2

I get this figure:

enter image description here

when I comment out the +ax.transData from the transform definition:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as patches
import matplotlib as mpl
from matplotlib.collections import PatchCollection

fig = plt.figure()
ax = fig.add_subplot(111)

myAngles=[0, -45, -90]
myColors=[30, 40, 50]
myPatches=[]

for color, angle in zip (myColors,myAngles):
    #r2 = patches.Rectangle((0,0), 20, 40, color=color,  alpha=0.50)
    r2 = patches.Rectangle((0,0), 20, 40)
    t2 = mpl.transforms.Affine2D().rotate_deg(angle) #+ ax.transData
    r2.set_transform(t2)
    #ax.add_patch(r2)
    myPatches.append(r2)

    plt.xlim(-20, 60)
    plt.ylim(-20, 60)

    plt.grid(True)


collection = PatchCollection(myPatches, cmap=mpl.cm.jet, alpha=0.5)
collection.set_array(np.array(myColors))
ax.add_collection(collection)

fig.savefig('withoutTransData.png')
plt.show()
Yann
  • 33,811
  • 9
  • 79
  • 70
  • 1
    Thank you Yann. That exaclt what I wanted, I was looking at the wrong place all the time. Now I am just a little confused about this additional translation +ax.transData that is sometimes necessary and sometimes not. – Piccolo Sep 20 '11 at 13:41