I want to generate a map of the United States and color each state in using a different shade. Is there a way to do this using Python's basemap?
Asked
Active
Viewed 2.0k times
1 Answers
25
There is a nicely formated example in the Basemap repo on GitHub: fillstates.py. The shapefile (dbf | shp | shx) is also included in the examples folder.
Here is an abbreviated version of the example:
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.patches import Polygon
# create the map
map = 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'
map.readshapefile('st99_d00', name='states', drawbounds=True)
# collect the state names from the shapefile attributes so we can
# look up the shape obect for a state by it's name
state_names = []
for shape_dict in map.states_info:
state_names.append(shape_dict['NAME'])
ax = plt.gca() # get current axes instance
# get Texas and draw the filled polygon
seg = map.states[state_names.index('Texas')]
poly = Polygon(seg, facecolor='red',edgecolor='red')
ax.add_patch(poly)
plt.show()
Resulting plot with Texas filled red:
Note that when we load a shapefile the shapes and attributes are stored in map.states
and map.states_info
respectively as lists based on the name
parameter used in the readshapefile
call. So to look up the shape for a specific state we had to build a corresponding list of the state names from the attributes.

Weston
- 2,732
- 1
- 28
- 34
-
That's really great. If I want to put a star on a particular lat/lon, how would I add that? – vy32 Jun 15 '16 at 15:54
-
@vy32 here is a good [example of plotting point data on a map](https://www.getdatajoy.com/examples/python-plots/plot-data-points-on-a-map), all of the marker styles can be found in the [matplotlib documentation](http://matplotlib.org/api/markers_api.html), specifically `*` is the start marker. – Weston Jun 22 '16 at 16:44
-
1@GonzaloGarcia absolutely, it just depends on the shapefile having a "NAME" field for each polygon. – Weston Nov 06 '19 at 10:20
-
How to add the state name or abbreviation, or plot data at a state? – ASE Oct 22 '21 at 03:14