【问题标题】:Multicolor for citites in geopandasgeopandas中城市的多色
【发布时间】:2020-02-21 04:57:07
【问题描述】:

我可以使用 geopandas 读取形状文件,但我想用一个州的不同颜色为不同的城市着色,我如何为一个州的不同城市着色不同的颜色? 谢谢你。

        import geopandas as gpd

       gf_states = gpd.read_file('IND_adm2.shp')
gr_states.head()
    ID_0    ISO     NAME_0  ID_1    NAME_1  ID_2    NAME_2  TYPE_2  ENGTYPE_2   NL_NAME_2   VARNAME_2   geometry
0   105     IND     India   1   Andaman and Nicobar     1   Andaman Islands     District    District    None    None    MULTIPOLYGON (((93.64841 14.93487, 93.64917 14...
1   105     IND     India   1   Andaman and Nicobar     2   Nicobar Islands     District    District    None    None    MULTIPOLYGON (((92.78778 9.24417, 92.78889 9.2...
2   105     IND     India   2   Andhra Pradesh  3   Anantapur   District    District    None    Anantpur, Ananthapur    POLYGON ((77.69000 15.17628, 77.69378 15.17347...
3   105     IND     India   2   Andhra Pradesh  4   Chittoor    District    District    None    Chitoor|Chittor     POLYGON ((78.47611 13.93680, 78.48208 13.93007...
4   105     IND     India   2   Andhra Pradesh  5   Cuddapah    District    District    None    None    POLYGON ((78.94612 15.19465, 78.95062 15.18535...

这里假设我想为 NAME_2 着色(Anantapur 为红色,chittor 为蓝色,cuddapah 为黄色等一个州 NAME_1 Andhra Pradesh)。我怎么能这样做? 谢谢。 我正在处理的代码如下:-

def fig_beauty_hires(ax,xlim=[66,78],ylim=[20,24],st_name,states=False,states_name=False):


import cartopy as crs
import cartopy.crs as ccrs
import cartopy.feature as cfeature
from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER
import geopandas as gpd

gf_states = gpd.read_file('IND_adm2.shp')
gdff = gf_states.loc[gf_states['NAME_1']==st_name,['geometry','NAME_2']]

if states_name:
    gf_new = gdff.cx[xlim[0]:xlim[1],ylim[0]:ylim[1]]
    state_points = gf_new.geometry.apply(lambda x :x.representative_point().coords[:])
    state_coords = [point[0] for point in state_points]

    cMap = ['#00FF00','#FFFF00','#00FFFF','#FF00FF','#FF4500','#7B68EE','#ADFF2F']
    for name, coord , col,j in zip(gf_new.NAME_2,state_coords,cMap,range(0,len(cMap))):
        #print(name)
        #ax.add_geometries(gdff.geometry,crs=ccrs.PlateCarree(),color=cMap[j],edgecolor='k')

        if name=="Nashik" or name=="Aurangabad"or name=="Jalna" or name=="Osmanabad"or name=="Gadag"or name=="Bellary"or                            name=="Mysore" or name=="Davanagere" or name=="Hassan" or name=="Greater Bombay"or name=="Thiruvananthapuram"or                          name=="Alappuzha" or name=="Kollam" or name=="Pattanamtitta" or name=="Idukki" or name=="Palakkad":
            print("if j:",str(cMap[j]))
            ax.add_geometries(gdff.geometry,crs=ccrs.PlateCarree(),facecolor=cMap[j],edgecolor='k')
            ax.text(x=coord[0],y=coord[1],s=" ",horizontalalignment='center',fontweight='normal',fontsize=10,color='k')

        else:
            print("else j:",str(cMap[j]))
            ax.add_geometries(gdff.geometry,crs=ccrs.PlateCarree(),facecolor=cMap[j],edgecolor='k')
            ax.text(x=coord[0],y=coord[1],s=name,horizontalalignment='center',fontweight='bold',fontsize=10,color='k')
if __name__=="__main__":
    import cartopy.crs as ccrs
    import cartopy.feature as cfeature

    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER                

    fig, ax = plt.subplots(figsize=(19.20,10.80), subplot_kw={'projection': ccrs.PlateCarree()})  
    fig_beauty_hires(ax=ax)

【问题讨论】:

    标签: python matplotlib geopandas cartopy


    【解决方案1】:

    目前还不完全清楚,您期望的最终输出是什么。而且您发布的代码无法运行(即使我们忽略了多个导入等)。

    我的理解是,您想要绘制一些几何图形,以便能够控制每个几何图形的 facecolor。这是一个简单的 sn-p,您可以在此基础上进行构建:(我设法找到了一个与您发布的数据集相匹配的数据集。)

    import geopandas as gpd
    import matplotlib.pyplot as plt
    import cartopy.crs as ccrs
    from cartopy.feature import ShapelyFeature
    
    # Obtain the data & keep only relevant attributes
    states = gpd.read_file('gadm36_IND.gpkg', layer=1)[['NAME_1', 'NAME_2', 'geometry']]
    
    # Prepare the data for easy manipulations later
    df = states[states.NAME_1 == 'Andhra Pradesh']
    df.reset_index(inplace=True, drop=True) #for later convenience
    
    # Prepare the projections
    data_crs = ccrs.PlateCarree() # this will be fixed by your data
    proj_crs = ccrs.PlateCarree() # this determines the projection of the plot
    extents = [75, 86, 12, 20] # change as needed depending on the data
    
    # Produce the main figure and axis
    fig = plt.figure(figsize=(15, 15))
    ax = fig.add_subplot(projection=proj_crs)
    
    # Some configuration
    ax.set_extent(extents, crs=data_crs)
    ax.coastlines() # just for (some) spatial reference only
    
    # Plot the geometries. A very basic plotting scheme shown here
    colours = ['red', 'green', 'yellow'] # (almost) randomly selected
    for index, row in df.iterrows():
        sp = ShapelyFeature(row.geometry, data_crs,
                            edgecolor='k', linewidth=0.5,
                            facecolor=colours[index%len(colours)])
        ax.add_feature(sp)
        locxy = row.geometry.representative_point()
        ax.annotate(row.NAME_2, xy=(locxy.x, locxy.y)) # use transform for other projections
    
    plt.show()
    

    The resulting plot

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-02
      • 1970-01-01
      • 2023-03-06
      • 2019-08-04
      • 1970-01-01
      • 2018-10-12
      • 2016-08-29
      • 2017-10-25
      相关资源
      最近更新 更多