首页 > 解决方案 > 为什么此示例中的图形大小(y 轴)会波动?

问题描述

我有一张世界地图,我在 for 循环中迭代地绘制干旱地区。

为了重现性,数据在这里:https ://data.humdata.org/dataset/global-droughts-events-1980-2001

import pandas as pd
import geopandas as gpd

import matplotlib.pyplot as plt
import seaborn as sns

from IPython.display import clear_output
sns.set_theme(style='whitegrid')

dr_geometry = gpd.read_file('data/dr_events.shp')
world_geometry = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

for y in dr_geometry.year.unique():
    clear_output(wait=True)
    fig, ax = plt.subplots(1, 1, figsize=(15, 15))
    world_geometry.plot(ax=ax)
    dr_geometry[dr_geometry.year == y].plot(ax=ax, color='red', edgecolor='black', linewidth=0.1)
    plt.show();
    

这工作正常,除了 y 轴在每次迭代时收缩或扩展一个很小但非常明显的量,导致动画不连贯。我怎样才能消除这种行为?

注意:显式设置ylim不会改变这一点。我还尝试将subplots实例化移到 for 循环之外,但这会导致输出为空。

迭代输出:

在此处输入图像描述

标签: pythonmatplotlibseaborngeopandas

解决方案


ax.set_aspect('equal')防止我的转变:

for y in dr_geometry.year.unique():
    clear_output(wait=True)
    fig, ax = plt.subplots(1, 1, figsize=(15, 15))
    world_geometry.plot(ax=ax)
    dr_geometry[dr_geometry.year == y].plot(ax=ax, color='red', edgecolor='black', linewidth=0.1)
    
    # set aspect ratio explicitly
    ax.set_aspect('equal')
    
    plt.show();

感谢@martinfleis指出转变的原因:

.plot()现在自动确定 GeoSeries(或 GeoDataFrame)是否在地理或投影 CRS 中,并使用1/cos(s_y * pi/180)withs_y作为 GeoSeries y 边界平均值的 y 坐标来计算地理的方面。与当前硬编码的“相等”方面相比,这可以更好地表示实际形状。


推荐阅读