首页 文章

用Python 3.2中的Matplotlib底图填写每个不同颜色的邮政编码

提问于
浏览
1

我正在着手在Python 3.2的Matplotlib底图中着色zip-code polygon .

我需要用不同的颜色填写每个邮政编码 .

邮政编码信息来自shapefile .

我找不到解决方案:http://matplotlib.org/basemap/api/basemap_api.html

任何帮助,将不胜感激 .

谢谢

1 回答

  • 2

    Basemap有一个非常方便的方式来读取shapefile .

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

    然后,您可以使用 m.namem.name_info 访问shapefile上的信息 .

    然后创建要用于颜色信息的数据帧 .

    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]
    })
    

    如果要包含shapefile中未包含的着色信息,请将该其他信息与刚刚创建的DataFrame合并 .

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

    现在,为了实际着色 Map ,我使用了一个颜色图,它采用了邮政编码中的租赁价格值,所以我会说明 .

    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()
    

    有关这方面的更多信息,请查看http://www.datadependence.com/2016/06/creating-map-visualisations-in-python/ .

    如果我遗漏了东西,请告诉我!

相关问题