1

I have a dataframe, State, containing state names and counts for each state. I am trying to create a map that colors the states based on the count by using the st99_d00 shapefiles. Here is my code:

import matplotlob.pyplot as plt
from matplotlib.patches import Polygon
from matplotlib.collections import PatchCollection
fig,MapAx = plt.subplots()
colorVotes = plt.get_cmap('coolwarm')
colors = []
patches = []
# create the map
m = Basemap(llcrnrlon=-119,llcrnrlat=22,urcrnrlon=-64,urcrnrlat=49,
    projection='lcc',lat_1=33,lat_2=45,lon_0=-95)

# load the shapefile, use the name 'states'
m.readshapefile('st99_d00', name='states', drawbounds=True)

# collect the state names from the shapefile attributes so we can
# look up the shape object for a state by it's name
state_names = []
for shape_dict in m.states_info:
    state_names.append(shape_dict['NAME'])

for state in State.StateNames:
    seg = m.states[state_names.index('{}'.format(state))]
    color = colorVotes(State['count'][State.StateNames == 
state]/float(max(State['count'])))[0]
    colors.append(color)
    poly= Polygon(seg, facecolor=color, edgecolor=color)
    patches.append(poly)
    MapAx.add_patch(poly)

p = PatchCollection(patches, cmap=colorVotes)
p.set_array(np.array(colors))
cb = fig.colorbar(p)
plt.show()

The above code returns the following map:enter image description here

enter image description here

Notice both Michigan and Wisconsin are not colored, however both states exist and have values in my data set.

2
  • You are joining on a string, so there must be a difference between the two names. It can be visible (trailing space, case, typo) or hidden (like a cariage return). You can copy/paste the name from one layer to the other
    – JGH
    Apr 23 '18 at 17:31
  • Have you checked that those geometries are valid?
    – user30184
    Apr 23 '18 at 18:46
2

Several states have more than one (seg), you only map the very first seg of each state. If You look closely You'll see Isle Royale has color, because that is the first polygon in Michigan.

You need to iterate over all m.states aka:

for i, seg in enumerate(m.states):
    #print("name:{}, shape:{}".format(state_names[i], seg))
    poly = Polygon(seg, facecolor='blue', edgecolor='blue')
    patches.append(poly)
    MapAx.add_patch(poly)

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .