Matplotlib:在Python中旋转图形(补丁)并应用颜色

1 投票
1 回答
3649 浏览
提问于 2025-04-17 02:34

我想对一个图形进行不同的变换,包括旋转和改变填充颜色。这里有一段代码,是参考了Matplotlib: 旋转图形的内容。

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

不幸的是,当我退出循环时,变换就丢失了。如果我在循环里面把图形添加到轴上,那一切都没问题。但我必须在最后再添加,因为颜色是在循环中收集的,应该在后面应用。

任何建议都非常感谢。

祝好

阿梅尔

1 个回答

2

我得到了这个图:

在这里输入图片描述

当我把 +ax.transData 从变换定义中注释掉的时候:

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

撰写回答