底图 - 状态颜色的Colorbar图例

时间:2016-03-11 16:14:07

标签: python matplotlib matplotlib-basemap

我有一个底图贴图,它加载在美国各州的shapefile中,对于每种状态,我将某种颜色映射到一个状态形状的多边形,然后将其添加到绘图中。添加这些多边形和颜色是成功的,但我遇到的问题是我想要一个显示最大颜色和最小颜色之间的渐变的图例,但我似乎无法弄清楚如何。 colorbar()方法想要一个mappable,我不确定我的例子是否可行,因为我使用Polygons为地图着色而不是imshow()或轮廓。以下是我写的代码。

mapAx.set_title("# of votes for Trump")

mapVotes = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
        projection='lcc',lat_1=33,lat_2=45,lon_0=-95)     
mapVotes.readshapefile('states', name = 'states', drawbounds=True)

colorVotes = plt.get_cmap('Blues')

trump = {
'New Hampshire': 100406,
'Iowa': 45427,
'South Carolina' : 239851,
'Nevada' : 34531}

state_names = []
for shape_dict in mapVotes.states_info:
    state_names.append(shape_dict['STATE_NAME'])


for state, value in trump.items():
    #print("{} {}".format(state, value)
    try:
        seg = mapVotes.states[state_names.index('{}'.format(state))]
        color = colorVotes(value/float(trump[max(trump)]))
        poly= Polygon(seg, facecolor=color, edgecolor=color)
        mapAx.add_patch(poly)
    except ValueError:
        pass

plt.show()

1 个答案:

答案 0 :(得分:3)

patch_collection的api示例显示了如何使用颜色栏。基本上,您将所有补丁添加到列表中,然后将其传递给PatchCollection,后者返回一个scalermappable。在您的具体情况下:

#empty lists for colors and polygons
colors = []
patches = []

for state, value in trump.items():
#print("{} {}".format(state, value)
try:
    seg = mapVotes.states[state_names.index('{}'.format(state))]
    color = colorVotes(value/float(trump[max(trump)]))
    colors.append(color) # add colors to colors list
    poly = Polygon(seg, facecolor=color, edgecolor=color)
    patches.append(poly) #add polygon to patches list
    mapAx.add_patch(poly)
except ValueError:
    pass

#new code
#patches collection is a scalermappable
p = PatchCollection(patches, cmap=colorVotes)
p.set_array(np.array(colors))
cb = fig.colorbar(p)

然后修改cb以显示正确的值。或者根据您的着色方案创建一个mcolor规范,并将其传递给PatchCollection或colorbar。但上面的代码产生: enter image description here