首页 > 解决方案 > 底图 Matplotlib 颜色栏

问题描述

我正在使用 matplotlib 和底图来生成美国地图和按人口着色的州。我可以显示地图并按人口着色(使用“热”色标),但在尝试显示彩条时遇到了麻烦。这是我显示地图和着色状态的方式:

m = Basemap(llcrnrlon=-121,llcrnrlat=20,urcrnrlon=-62,urcrnrlat=51,projection='lcc',lat_1=32,lat_2=45,lon_0=-95)

shp_info = m.readshapefile('st99_d00','states',drawbounds=True)

colors={}
statenames=[]
cmap = plt.cm.hot
vmin = 0
vmax = 100000000 
for shapedict in m.states_info:
    statename = shapedict['NAME']
    # skip DC and Puerto Rico.
    if statename not in ['District of Columbia','Puerto Rico']:
        stateabbrev = conversiondict2[statename]
        rate = statedict[stateabbrev]
        colors[statename] = cmap(1.-np.sqrt((rate-vmin)/(vmax-vmin)))[:3]
    statenames.append(statename)

ax = plt.gca()

for nshape,seg in enumerate(m.states):
    # skip DC and Puerto Rico.
    if statenames[nshape] not in ['Puerto Rico', 'District of Columbia']:
        color = rgb2hex(colors[statenames[nshape]])
    # Offset Alaska and Hawaii to the lower left corner. 
        if statenames[nshape] == 'Alaska': 
            seg = list(map(lambda (x,y): (0.35*x + 1100000, 0.35*y-1300000), seg))
        elif statenames[nshape] == 'Hawaii':
            seg = list(map(lambda (x,y): (x + 5100000, y-1400000), seg))
        poly = Polygon(seg,facecolor=color,edgecolor="black",zorder=0)
        ax.add_patch(poly)

m.colorbar(cmap, ax=ax)
plt.show()

请注意,为简洁起见,我省略了我的州和缩写转换字典。没有 m.colorbar(cmap, ax=ax) 行,这显示很好,但是当我尝试添加颜色条时,我得到了这个错误:

AttributeError: 'LinearSegmentedColormap' object has no attribute 'autoscale_None'

也许我不完全理解 Basemap colorbar 函数的工作原理,但我认为在我的情况下 cmap 将是可映射参数(颜色渐变),而 ax 将是轴限制?任何帮助,将不胜感激。

标签: pythonmatplotlibmatplotlib-basemap

解决方案


推荐阅读