用于补丁收集的颜色的图例

问题描述 投票:1回答:1

我有通过标量值(整数)着色的补丁。现在我想创建一个图例,为某个颜色/整数值的补丁命名。这是我到目前为止尝试的内容:

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)

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

enter image description here

python matplotlib
1个回答
1
投票

您需要对要提供给色彩映射的值进行标准化。理想情况下,您已将此规范化提供给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

© www.soinside.com 2019 - 2024. All rights reserved.