在美国的底图中为多边形添加颜色条

Add colorbar for polygones in basemap plot of US

非常感谢您为以下代码绘制颜色条的任何帮助。 I want my figure to be like this

我正在使用形状文件和下面提到的文件根据字典对象中可用的密度绘制颜色图。

            {'ALABAMA': 37,
             'ALASKA': 1,
             'ARIZONA': 161,
             'ARKANSAS': 35,
             'CALIFORNIA': 1854,
             'COLORADO': 104,
             'CONNECTICUT': 170,
             'DELAWARE': 53,
             'DISTRICT OF COLUMBIA': 83,
             'FLORIDA': 364,
             'GEORGIA': 350,
             'HAWAII': 15,
             'IDAHO': 16,
             'ILLINOIS': 553,
             'INDIANA': 109,
             'IOWA': 60,
             'KANSAS': 47,
             'KENTUCKY': 50,
             'LOUISIANA': 48,
             'MAINE': 17,
             'MARYLAND': 187,
             'MASSACHUSETTS': 351,
             'MICHIGAN': 260,
             'MINNESOTA': 170,
             'MISSISSIPPI': 16,
             'MISSOURI': 119,
             'NA': 11,
             'NEBRASKA': 28,
             'NEVADA': 21,
             'NEW HAMPSHIRE': 32,
             'NEW JERSEY': 676,
             'NEW MEXICO': 20,
             'NEW YORK': 993,
             'NORTH CAROLINA': 266,
             'NORTH DAKOTA': 5,
             'OHIO': 271,
             'OKLAHOMA': 32,
             'OREGON': 77,
             'PENNSYLVANIA': 367,
             'PUERTO RICO': 5,
             'RHODE ISLAND': 37,
             'SOUTH CAROLINA': 40,
             'SOUTH DAKOTA': 9,
             'TENNESSEE': 95,
             'TEXAS': 954,
             'UTAH': 52,
             'VERMONT': 10,
             'VIRGINIA': 278,
             'WASHINGTON': 351,
             'WEST VIRGINIA': 10,
             'WISCONSIN': 127,
             'WYOMING': 3}

这是我的代码

            import matplotlib as mpl
            from matplotlib.collections import PatchCollection
            fig,ax=plt.subplots()


            m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
            # draw state boundaries.

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


            popdensity = top10states.set_index('STATES').to_dict()['NOOFAPPS']




            # choose a color for each state based on population density.
            legendcolor = []
            colors={}
            statenames=[]
            patches = []

            cmap = plt.cm.summer 
            vmin = min(top10states["NOOFAPPS"])
            vmax = max(top10states["NOOFAPPS"]) 

            # norm = mpl.colors.Normalize(vmin=vmin, vmax=vmax, clip=False)
            # mapper=mpl.cm.ScalarMappable(cmap=cmap)


            for shapedict in m.states_info:
                statename = shapedict['NAME'].upper()
                if statename in popdensity:
                    pop = popdensity[statename]
                    colors[statename] = cmap(1.-np.sqrt((pop-vmin)/(vmax-vmin)))[:3]
                    statenames.append(statename)
                else:
                    statenames.append(statename)
                    colors[statename] = "darkorange"

            ax = plt.gca() # get current axes instance
            fig = plt.gcf()




            for nshape,seg in enumerate(m.states):

                color = rgb2hex(colors[statenames[nshape]]) 
                legendcolor.append(color)
                poly = Polygon(seg,facecolor=color,edgecolor=color)
                ax.add_patch(poly)
                patches.append(poly)

            mappble = plt.gci()

            # p = PatchCollection(patches, cmap=cmap)
            # p.set_array(np.array(legendcolor))
            # cb1 = mpl.colorbar.ColorbarBase(fig,cmap=cmap,norm=norm,orientation="horizontal")
            # cb = fig.colorbar.ColorbarBase(fig,cmap=cmap,norm=norm,orientation="horizontal")

            # fig.colorbar.ColorbarBase(fig,cmap=cmap,norm=norm,orientation="horizontal")
            # map.colorbar(norm=norm)
            plt.title('Filling State Polygons by Population Density')
            plt.show()

我尝试了一些评论的组合,但似乎对我没有任何效果

您已经使用 ColorbarBase 函数根据密度字典的值构建了自定义颜色条。您必须通过 ScalarMappable 转换的值。看评论:

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.colors import rgb2hex, Normalize
from matplotlib.cm import ScalarMappable
from matplotlib.patches import Polygon
from matplotlib.colorbar import ColorbarBase

m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
        projection='lcc',lat_1=33,lat_2=45,lon_0=-95)
ax = plt.gca() 
fig = plt.gcf()
shp_info = m.readshapefile('st99_d00','states',drawbounds=True)

popdensity = {'ALABAMA': 37,
 'ALASKA': 1,
 'ARIZONA': 161,
 'ARKANSAS': 35,
 'CALIFORNIA': 1854,
 'COLORADO': 104,
 'CONNECTICUT': 170,
 'DELAWARE': 53,
 'DISTRICT OF COLUMBIA': 83,
 'FLORIDA': 364,
 'GEORGIA': 350,
 'HAWAII': 15,
 'IDAHO': 16,
 'ILLINOIS': 553,
 'INDIANA': 109,
 'IOWA': 60,
 'KANSAS': 47,
 'KENTUCKY': 50,
 'LOUISIANA': 48,
 'MAINE': 17,
 'MARYLAND': 187,
 'MASSACHUSETTS': 351,
 'MICHIGAN': 260,
 'MINNESOTA': 170,
 'MISSISSIPPI': 16,
 'MISSOURI': 119,
 'NA': 11,
 'NEBRASKA': 28,
 'NEVADA': 21,
 'NEW HAMPSHIRE': 32,
 'NEW JERSEY': 676,
 'NEW MEXICO': 20,
 'NEW YORK': 993,
 'NORTH CAROLINA': 266,
 'NORTH DAKOTA': 5,
 'OHIO': 271}

nodata_color = "darkorange"
colors={}
statenames=[]
patches = []

cmap = plt.cm.summer
vmin = min(popdensity.values()); vmax = max(popdensity.values())
norm = Normalize(vmin=vmin, vmax=vmax)
# color mapper to covert values to colors
mapper = ScalarMappable(norm=norm, cmap=cmap)

for shapedict in m.states_info:
    statename = shapedict['NAME'].upper()
    if statename in popdensity:
        pop = popdensity[statename]
        colors[statename] = mapper.to_rgba(pop)
        statenames.append(statename)
    else:
        statenames.append(statename)
        colors[statename] = nodata_color

for nshape,seg in enumerate(m.states):
    color = rgb2hex(colors[statenames[nshape]]) 
    poly = Polygon(seg,facecolor=color,edgecolor=color)
    if (colors[statenames[nshape]] == nodata_color):
        p_no = poly
    ax.add_patch(poly)
plt.title('Filling State Polygons by Population Density')

# put legend for no data states
if p_no is not None:
    plt.legend((p_no,), ('No data',))

# construct custom colorbar
cax = fig.add_axes([0.27, 0.1, 0.5, 0.05]) # posititon
cb = ColorbarBase(cax,cmap=cmap,norm=norm, orientation='horizontal')
cb.ax.set_xlabel('Population density of U.S.A.')
plt.show()

我想水平颜色条更适合你的地图。