gpt4 book ai didi

python - 用于 patchcollection 的带有颜色的图例

转载 作者:太空宇宙 更新时间:2023-11-03 14:13:57 24 4
gpt4 key购买 nike

我有一些由标量值(整数)着色的补丁。现在我想创建一个图例,为特定颜色/整数值的补丁命名。这是我迄今为止尝试过的:

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

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

patches = []
cvect = []
for kx in range(10):
for ky in range(10):
patches.append(Polygon([(kx,ky),(kx,ky+1),(kx+1,ky+1),(kx+1,ky)]))
cvect.append(((kx*ky)%6))

cmap = plt.cm.get_cmap('jet')


pc = PatchCollection(patches,edgecolors='none',cmap=cmap)
pc.set_array(np.array(cvect))
ax.add_collection(pc)

clist = list(set(cvect))
handles = []
for col in clist:
handles.append(Polygon([(0,0),(10,0),(0,-10)],color=cmap(col),
label='Material %i'%(col)))

plt.legend(handles=handles)

ax.set_xlim([0,10])
ax.set_ylim([0,10])

fig.savefig('fig')
plt.close(fig)

但是图例中的颜色与具有相同整数值的色 block 的颜色不匹配。我做错了什么?

enter image description here

最佳答案

您需要对提供给颜色图的值进行标准化。理想情况下,您已经向 Collection pc 提供了这种标准化。然后您可以通过 pc.cmap(pc.norm(clist)) 访问颜色。

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

fig = plt.figure(figsize=(10,8))
ax = fig.add_subplot(111)

patches = []
cvect = []
for kx in range(10):
for ky in range(10):
patches.append(Polygon([(kx,ky),(kx,ky+1),(kx+1,ky+1),(kx+1,ky)]))
cvect.append(((kx*ky)%6))

cmap = plt.cm.get_cmap('jet')
norm = plt.Normalize(min(cvect), max(cvect))

pc = PatchCollection(patches,edgecolors='none',cmap=cmap, norm=norm)
pc.set_array(np.array(cvect))
ax.add_collection(pc)

clist = list(set(cvect))

handles = []
for col in clist:
print pc.norm(col)
handles.append(Polygon([(0,0),(10,0),(0,-10)],color=pc.cmap(pc.norm(col)),
label='Material %i'%(col)))

plt.legend(handles=handles)

ax.set_xlim([0,10])
ax.set_ylim([0,10])

plt.show()

enter image description here

关于python - 用于 patchcollection 的带有颜色的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48324708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com