代码之家  ›  专栏  ›  技术社区  ›  The Mad Scientist

试图用Python调整阿拉斯加和夏威夷以适应县级地图

  •  0
  • The Mad Scientist  · 技术社区  · 2 年前

    我需要为整个美国制作一张县级地图。我现在的问题是,我无法调整阿拉斯加和夏威夷,使它们位于我地图的左下角,加利福尼亚州下方和德克萨斯州左侧。到目前为止,我的计划如下,但它没有对阿拉斯加和夏威夷的规模和位置产生任何变化。

    import geopandas as gpd
    import matplotlib.pyplot as plt
    
    # Load the shapefile
    shape_path = '/Users/deas/Documents/Research/cb_2018_us_county_20m/cb_2018_us_county_20m.shp'
    shape = gpd.read_file(shape_path)
    
    # Territories to exclude
    to_exclude = ['03', '07', '14', '43', '52', '72']
    
    # Define a list of ALL state FIPS codes
    state_fips_codes = shape['STATEFP'].unique()
    
    # Exclude specified codes from the list
    state_fips_codes = [code for code in state_fips_codes if code not in to_exclude]
    
    # Filter the shapefile to include only the desired states
    shape = shape[shape['STATEFP'].isin(state_fips_codes)]
    shape = shape.sort_values('STATEFP')
    
    # Create a map with Alaska and Hawaii scaled and repositioned
    fig, ax = plt.subplots(figsize=(12, 6))
    
    # Plot the shapefile (continental US)
    shape.boundary.plot(ax=ax, edgecolor='black', linewidth=0.4)
    
    # Scale and reposition Alaska
    alaska = shape[shape['STATEFP'] == '02']
    alaska['geometry'] = alaska['geometry'].scale(xfact=0.4, yfact=0.4)  # Adjust the scaling factor
    alaska['geometry'] = alaska['geometry'].translate(xoff=-50, yoff=-70)  # Adjust the translation
    
    # Scale and reposition Hawaii
    hawaii = shape[shape['STATEFP'] == '15']
    hawaii['geometry'] = hawaii['geometry'].scale(xfact=0.5, yfact=0.5)  # Adjust the scaling factor
    hawaii['geometry'] = hawaii['geometry'].translate(xoff=-20, yoff=-100)  # Adjust the translation
    
    # Plot the modified Alaska and Hawaii
    alaska.boundary.plot(ax=ax, edgecolor='black', linewidth=0.4)
    hawaii.boundary.plot(ax=ax, edgecolor='black', linewidth=0.4)
    
    # Set the extent of the map to cover the entire US
    ax.set_xlim(-175, -60)
    ax.set_ylim(18, 72)
    
    # Turn off axis labels and ticks
    ax.get_xaxis().set_visible(False)
    ax.get_yaxis().set_visible(False)
    ax.axis('off')
    ax.set_aspect('equal')
    
    plt.title('Title', size=18, weight='bold')
    plt.show()
    

    我使用的是人口普查局的一个形状文件,列如下:

    Index(['STATEFP', 'COUNTYFP', 'COUNTYNS', 'AFFGEOID', 'GEOID', 'NAME', 'LSAD',
           'ALAND', 'AWATER', 'geometry'],
          dtype='object')
    

    最后,我需要用Python编写这个程序,我看到了一些R的答案,但没有看到Python的答案。如有任何帮助,我们将不胜感激!

    0 回复  |  直到 2 年前
    推荐文章