Reputation: 1082
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
Upvotes: 1
Views: 3686
Reputation: 35563
I get this figure:
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()
Upvotes: 2