gpt4 book ai didi

python - matplotlib:将图例颜色与 patchCollection 颜色匹配

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

我使用(简化的)以下代码在图像上覆盖补丁:

import matplotlib.pyplot as plt
from scipy.misc import imread
from matplotlib.collections import PatchCollection
from matplotlib.patches import Circle, Arrow
import numpy as np

def plotFeatures( patches, colours, legends, str_title, colour_scale ):

fig = plt.figure(); ax = plt.gca()

p = PatchCollection(patches, cmap=plt.get_cmap('Spectral_r'), alpha=0.9)
p.set_array(np.array(colours))
ax.add_collection(p)
p.set_clim(colour_scale)
fig.colorbar(p, ax=ax, fraction=0.015)
plt.xlabel(str_title)
plt.legend(handles=patches, labels=legends, bbox_to_anchor=(0., 1.02, 1., .2), mode='expand', ncol=3, loc="lower left")
# ax.set_xticks([]); ax.set_yticks([])
ax.set_xlim([0,100])
ax.set_ylim([0,100])


if __name__ == '__main__':

my_cmap = plt.get_cmap('Spectral_r')

# simplified data structure for example
allweights = [ {'name': 'Feature 1', 'mean': 2.1, 'x': 60, 'y':30},
{'name': 'Feature 2', 'mean': 3.0, 'x': 10, 'y':40},
{'name': 'Feature 3', 'mean': 2.5, 'x': 30, 'y':20} ]

KPD_patchList = []
KPD_colourList = []
KPD_legendList = []

for w in allweights:
KPD_patchList.append( Circle( (w['x'], w['y']), w['mean'] + 5 ) )
KPD_colourList.append( w['mean'] )
KPD_legendList.append( '{:s} ({:.2f})'.format( w['name'], w['mean']) )

plotFeatures( KPD_patchList, KPD_colourList, KPD_legendList, 'myFeatures', [0, 3] )

plt.show()

结果是: enter image description here

但是图例中的补丁没有正确的颜色。

我遇到的问题是我为 PatchColelction p 设置了颜色,但 plt.legend() 不接受 PatchColelction 作为句柄,我必须向它提供不包含颜色数据的补丁。

当我调用 Cricle 时,我尝试使用 facecolor=my_cmap(w['mean'] 直接将颜色数据添加到色 block ,如下所示:

for w in allweights:
KPD_patchList.append( Circle( (w['x'], w['y']), w['mean'] + 5, facecolor=my_cmap(w['mean']) ) )
KPD_colourList.append( w['mean'] )
KPD_legendList.append( '{:s} ({:.2f})'.format( w['name'], w['mean']) )

但是颜色的缩放比例并不像图中一样:

enter image description here

最佳答案

我认为您的第二次尝试是正确的,只是您的数据未针对颜色图正确标准化。当您尝试从颜色图中获取颜色值时,您需要提供 [0-1] 范围内的值。为了让事情变得更简单,我经常使用 matplotlib.cm.ScalarMappable ( link to documentation ) 自动处理此转换。

为了解决您的问题,我修改了函数 plotFeatures(),如下所示:

def plotFeatures( patches, colours, legends, str_title, colour_scale ):

fig = plt.figure(); ax = plt.gca()

p = PatchCollection(patches, cmap=plt.get_cmap('Spectral_r'), alpha=0.9)
p.set_array(np.array(colours))
ax.add_collection(p)
p.set_clim(colour_scale)
fig.colorbar(p, ax=ax, fraction=0.015)
plt.xlabel(str_title)

# generate legend
# create a `ScalarMappable` object with the colormap used, and the right scaling
cm = matplotlib.cm.ScalarMappable(cmap=p.get_cmap())
cm.set_clim(colour_scale)
# create a list of Patches for the legend
l = [Circle((None,None), facecolor=cm.to_rgba(mean_value)) for mean_value in colours]
# add legend to plot
plt.legend(handles=l, labels=legends, bbox_to_anchor=(0., 1.02, 1., .2), mode='expand', ncol=3, loc="lower left")


# ax.set_xticks([]); ax.set_yticks([])
ax.set_xlim([0,100])
ax.set_ylim([0,100])

enter image description here

关于python - matplotlib:将图例颜色与 patchCollection 颜色匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937630/

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