Geopandas 1.0.1创建三子图时轴传递异常问题求助
问题:Geopandas 1.0.1无法正确传递子图轴到绘图函数
使用Geopandas 1.0.1版本,尝试创建3个垂直排列的子图,但子图轴无法正确传递给Geopandas的plot函数,导致绘图结果不符合预期。
代码示例
import pandas as pd import geopandas as gpd from geopandas import GeoDataFrame import matplotlib.pyplot as plt df = pd.read_csv('/home/ruby/Desktop/degree.csv') # 注:原代码中读取国家边界数据的语句未实际使用,属于冗余代码 # gdf = gpd.read_file("https://naciscdn.org/naturalearth/110m/cultural/ne_110m_admin_0_countries.zip") fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(20,10)) geometry = gpd.points_from_xy(df.lon, df.lat) gdf = GeoDataFrame(df, crs="EPSG:4326", geometry=geometry) gdf.plot(ax=axes[0], column='degree', cmap='Blues', alpha=0.6, legend=True, markersize=10, legend_kwds={'label':"Avg degree",'orientation': "horizontal"}) gdf.plot(ax=axes[1], column='degree', cmap='Blues', alpha=0.6, legend=True, markersize=10, legend_kwds={'label':"Avg degree",'orientation': "horizontal"}) gdf.plot(ax=axes[2], column='degree', cmap='Blues', alpha=0.6, legend=True, markersize=10, legend_kwds={'label':"Avg degree",'orientation': "horizontal"}) plt.xlim([50.0, 130.0]) plt.ylim([0.0,40.0]) plt.show()
当前输出
当前运行后仅显示一个子图,其余子图被图例挤压覆盖,输出截图如下:
问题原因与解决方案
- 坐标范围仅作用于最后一个子图:
plt.xlim()和plt.ylim()默认只对当前活跃的子图(即最后创建的子图)生效,需要为每个子图单独设置范围。 - 图例布局冲突:每个子图都添加水平图例,会大幅占用垂直空间,导致子图重叠或被挤压消失。建议只在最后一个子图添加图例,或调整图例位置。
- 画布尺寸不足:原画布高度不足以容纳3个带水平图例的子图,需适当增大高度。
修正后的代码:
import pandas as pd import geopandas as gpd from geopandas import GeoDataFrame import matplotlib.pyplot as plt df = pd.read_csv('/home/ruby/Desktop/degree.csv') # 增大画布高度适配3个子图 fig, axes = plt.subplots(nrows=3, ncols=1, figsize=(20,15)) geometry = gpd.points_from_xy(df.lon, df.lat) gdf = GeoDataFrame(df, crs="EPSG:4326", geometry=geometry) # 第一个子图:隐藏图例,单独设置坐标范围 gdf.plot(ax=axes[0], column='degree', cmap='Blues', alpha=0.6, legend=False, markersize=10) axes[0].set_xlim([50.0, 130.0]) axes[0].set_ylim([0.0,40.0]) axes[0].set_title('子图1') # 第二个子图:隐藏图例,单独设置坐标范围 gdf.plot(ax=axes[1], column='degree', cmap='Blues', alpha=0.6, legend=False, markersize=10) axes[1].set_xlim([50.0, 130.0]) axes[1].set_ylim([0.0,40.0]) axes[1].set_title('子图2') # 第三个子图:显示图例,单独设置坐标范围,调整图例间距 gdf.plot(ax=axes[2], column='degree', cmap='Blues', alpha=0.6, legend=True, markersize=10, legend_kwds={'label':"Avg degree",'orientation': "horizontal", 'pad':0.1}) axes[2].set_xlim([50.0, 130.0]) axes[2].set_ylim([0.0,40.0]) axes[2].set_title('子图3') # 自动调整子图间距,避免重叠 plt.tight_layout() plt.show()
关键修正点
- 对每个子图单独调用
set_xlim()和set_ylim()设置坐标范围 - 仅在最后一个子图添加图例,避免布局冲突
- 增大画布高度并使用
plt.tight_layout()优化子图间距 - 为每个子图添加标题用于区分
内容的提问来源于stack exchange,提问作者Ruby
相关产品推荐
相关产品推荐

