3

I am working on coloring zip-code polygon in a basemap of Matplotlib in Python 3.2.

I need to fill in each zip-code with a different color.

The zip-code information comes from shapefile.

I cannot find solutions at: http://matplotlib.org/basemap/api/basemap_api.html

Any help would be appreciated.

Thanks

user3601704
  • 753
  • 1
  • 14
  • 46

2 Answers2

4

Basemap has a pretty handy way to read in a shapefile.

m = Basemap()
m.readshapefile('file_without_extension', 'name')

You can then access information on the shapefile with m.name and m.name_info.

Then create the dataframe you want to use for color info.

import pandas as pd
import numpy as np
from matplotlib.patches import Polygon

zipdf = pd.DataFrame({
    'shapes': [Polygon(np.array(shape), True) for shape in m.name],
    'zip': [area['zip'] for area in m.name_info]
})

If you want to include information for coloring that is not included in the shapefile, merge that other info with the DataFrame you just created.

zipdf = zipdf.merge(other_df, how='right', on='zip')

Now for actually coloring the map, I used a colormap that takes values for rental prices in the zipcode, so I'll show that.

from matplotlib.collections import PatchCollection
import matplotlib.cm as cm
import matplotlib.colors as colors

fig = plt.figure()
ax = fig.add_subplot(111)

cmap = plt.get_cmap('viridis')
pc = PatchCollection(zipdf['shapes'], zorder=2)
norm = colors.Normalize()

pc.set_facecolor(cmap(norm(zipdf['price'].values)))
ax.add_collection(pc)

cmapper = cm.ScalarMappable(norm=norm, cmap=cmap)
cmapper.set_array(zipdf['price'])
plt.colorbar(cmapper)

plt.show()

For a bit more on this, check out Creating Attractive and Informative Map Visualisations in Python with Basemap from Data Dependence.

Henry Woody
  • 14,024
  • 7
  • 39
  • 56
0

Complementing the above answer, you can find the aforementioned 'file without extension' for us zip codes here

Marlon Teixeira
  • 334
  • 1
  • 14