Matplotlib: Rotating a figure (patch) and applying colors in python

折月煮酒 提交于 2019-12-11 11:21:27

问题


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


回答1:


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


来源:https://stackoverflow.com/questions/7467631/matplotlib-rotating-a-figure-patch-and-applying-colors-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!