Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fill in each zip-code with a different color for basemap of Matplotlib in Python 3.2

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

like image 641
user3601704 Avatar asked Nov 20 '25 00:11

user3601704


1 Answers

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.

like image 185
Henry Woody Avatar answered Nov 22 '25 15:11

Henry Woody



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!