GeoPandas 多图中共享图例

Jon*_*nas 2 python matplotlib geopandas

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

我知道有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()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

Rut*_*ies 6

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

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

在这种情况下,每个轴只有 1 个(补丁集合),并且每个轴都是相同的。因此,使用 fetch 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述