本文介绍了Matplotlib:旋转图形(补丁)并在 python 中应用颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想对补丁应用不同的转换,包括旋转和改变填充颜色.更高的代码段已经受 Matplotlib启发:旋转补丁

I want to apply different transformations to a patch, includingrotating 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()

不幸的是,当我退出for循环时,转换丢失了.如果我将补丁添加到循环中的斧头,那么一切都很好.但是我必须在最后做,因为颜色是在循环中收集的,应该稍后再应用.

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

欢呼

Armel

推荐答案

我得到这个数字:

当我从转换定义中注释掉 +ax.transData 时:

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

这篇关于Matplotlib:旋转图形(补丁)并在 python 中应用颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 15:32