【问题标题】:Color states with Python's matplotlib/basemap使用 Python 的 matplotlib/basemap 着色状态
【发布时间】:2011-09-28 16:23:41
【问题描述】:

我想生成一张美国地图,并使用不同的阴影为每个州着色。有没有办法使用 Python 的底图来做到这一点?

【问题讨论】:

    标签: python matplotlib gis


    【解决方案1】:

    在 GitHub 上的 Basemap 存储库中有一个格式很好的示例:fillstates.py。 shapefile (dbf | shp | shx) 也包含在 examples folder 中。

    以下是示例的缩略版:

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

    德克萨斯州填充红色的结果图:

    请注意,当我们加载 shapefile 时,形状和属性分别作为列表存储在 map.statesmap.states_info 中,这些列表基于 readshapefile 调用中使用的 name 参数。因此,要查找特定状态的形状,我们必须根据属性构建相应的状态名称列表。

    【讨论】:

    • 这真的很棒。如果我想在特定的纬度/经度上加一颗星,我该如何添加?
    • @vy32 这里是一个很好的example of plotting point data on a map,所有的标记样式都可以在matplotlib documentation中找到,特别是*是开始标记。
    • @GonzaloGarcia 绝对是,它只取决于每个多边形都有一个“NAME”字段的 shapefile。
    • 如何添加州名或缩写,或在州内绘制数据?
    猜你喜欢
    • 2015-08-11
    • 1970-01-01
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多