MatPlotLib + GeoPandas:绘制多个图层,控制图

时间:2016-08-29 21:04:38

标签: python-3.x matplotlib figure geopandas

给定形状文件可用here:我知道可以用县标签甚至地图上的某些点生成我需要的基本地图(见下文)。我遇到的问题是我无法用figsize控制图形的大小。 这就是我所拥有的:

import geopandas as gpd
import matplotlib.pyplot as plt
%matplotlib inline
figsize=5,5
fig = plt.figure(figsize=(figsize),dpi=300)

shpfileshpfile=r'Y:\HQ\TH\Groups\NR\PSPD\Input\US_Counties\cb_2015_us_county_20m.shp' 
c=gpd.read_file(shpfile)
c=c.loc[c['GEOID'].isin(['26161','26093','26049','26091','26075','26125','26163','26099','26115','26065'])]
c['coords'] = c['geometry'].apply(lambda x: x.representative_point().coords[:])
c['coords'] = [coords[0] for coords in c['coords']]
ax=c.plot()

#Control some attributes regarding the axis (for the plot above)   

ax.spines['top'].set_visible(False);ax.spines['bottom'].set_visible(False);ax.spines['left'].set_visible(False);ax.spines['right'].set_visible(False)
    ax.tick_params(axis='y',which='both',left='off',right='off',color='none',labelcolor='none')
    ax.tick_params(axis='x',which='both',top='off',bottom='off',color='none',labelcolor='none')
    for idx, row in c.iterrows():
        ax.annotate(s=row['NAME'], xy=row['coords'],
                     horizontalalignment='center')
lat2=[42.5,42.3]
lon2=[-84,-83.5]

   #Add another plot...

ax.plot(lon2,lat2,alpha=1,marker='o',linestyle='none',markeredgecolor='none',markersize=15,color='white')
plt.show()

如您所见,我选择按轴名称调用绘图,因为我需要控制轴的属性,例如tick_params。我不确定是否有更好的方法。这似乎是“毫无疑问”,但我似乎无法弄清楚为什么我无法控制数字大小。

提前致谢!

1 个答案:

答案 0 :(得分:2)

我只需要做以下事情:

  1. 使用fig, ax = plt.subplots(1, 1, figsize = (figsize))
  2. 2.在c.plot()

    中使用ax = ax参数
    import geopandas as gpd
    import matplotlib.pyplot as plt
    %matplotlib inline
    figsize=5,5
    #fig = plt.figure(figsize=(figsize),dpi=300)
    #ax = fig.add_subplot(111)
    fig, ax = plt.subplots(1, 1, figsize = (figsize))
    shpfileshpfile=r'Y:\HQ\TH\Groups\NR\PSPD\Input\US_Counties\cb_2015_us_county_20m.shp' 
    c=gpd.read_file(shpfile)
    c=c.loc[c['GEOID'].isin(['26161','26093','26049','26091','26075','26125','26163','26099','26115','26065'])]
    c['coords'] = c['geometry'].apply(lambda x: x.representative_point().coords[:])
    c['coords'] = [coords[0] for coords in c['coords']]
    c.plot(ax=ax)
    ax.spines['top'].set_visible(False);ax.spines['bottom'].set_visible(False);ax.spines['left'].set_visible(False);ax.spines['right'].set_visible(False)
    ax.tick_params(axis='y',which='both',left='off',right='off',color='none',labelcolor='none')
    ax.tick_params(axis='x',which='both',top='off',bottom='off',color='none',labelcolor='none')
    for idx, row in c.iterrows():
        ax.annotate(s=row['NAME'], xy=row['coords'],
                     horizontalalignment='center')
    lat2=[42.5,42.3]
    lon2=[-84,-83.5]
    ax.plot(lon2,lat2,alpha=1,marker='o',linestyle='none',markeredgecolor='none',markersize=15,color='white')