首页 > 解决方案 > GeoPandas 多图中的共享图例

问题描述

GeoDataFrame.plot()我正在为每个月创建一个带有 GeoPandas子图的多图。如何为所有子图共用图例以及 x 和 y 轴并控制 figsize?

我知道有sharex=Truesharey=True但我不知道放在哪里。

plt.figure(sharex=True, sharey=True)返回TypeError: __init__() got an unexpected keyword argument 'sharex'

world.plot(column='pop_est', ax=ax, legend=True, sharex=True, sharey=True)返回AttributeError: 'PatchCollection' object has no property 'sharex'

ax = plt.subplot(4, 3, index + 1, sharex=True, sharey=True)返回TypeError: cannot create weak reference to 'bool' object

import pandas as pd
import geopandas as gpd
import matplotlib.pyplot as plt

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

months = pd.DataFrame(["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"],
                      columns = ['months'])

plt.figure()

for index, i in months.iterrows():
    ax = plt.subplot(4, 3, index + 1) # nrows, ncols, axes position
    world.plot(column='pop_est', ax=ax, legend=True)
    ax.set_title(index)
    ax.set_aspect('equal', adjustable='datalim')

plt.suptitle('This is the figure title', fontsize=12, y=1.05)
plt.tight_layout()
plt.show()

在此处输入图像描述

标签: pythonmatplotlibgeopandas

解决方案


@ImportanceOfBeingErnest 在上面的评论中已经解释了shared_xand关键字。share_y效果很好,如果您实际上是在展示整个世界,我会亲自删除所有刻度/标签。但对于子集,它可能会有所帮助。

创建共享图例(Matplotlib 将其称为颜色条,而不是图例)有点挑剔,因为 Geopandas 不返回轴而不是 mapabble(就像 Matplotlib 通常那样)。一个简单的解决方法是从轴集合中获取它,但这确实需要一些假设,如果有多个,您需要哪个可映射。

在这种情况下,每个轴只有 1 个(补丁集合),并且每个轴都是相同的。所以获取 ithaxs[0].collections[0]很简单,但不是最强大的解决方案。

另一种方法是创建前期并使用关键字将其cax提供给 Geopandas 图。cax=cax但是cax手动创建(使用 fig.add_axes([]) 不太方便。

fig.colorbar如下所示使用似乎更容易,因为它允许cax基于轴列表/数组创建。

fig, axs = plt.subplots(4,3, figsize=(10,7), 
                        facecolor='w',
                        constrained_layout=True, 
                        sharex=True, sharey=True, 
                        subplot_kw=dict(aspect='equal'))

axs = axs.ravel()

fig.suptitle('This is the figure title', fontsize=12, y=1.05)

for index, i in months.iterrows():

    axs[index].set_title(index)
    world.plot(column='pop_est', ax=axs[index])


# assume it's the first (and only) mappable
patch_col = axs[0].collections[0]
cb = fig.colorbar(patch_col, ax=axs, shrink=0.5)

在此处输入图像描述


推荐阅读