簡體   English   中英

GeoPandas 多圖中的共享圖例

[英]Shared legend in GeoPandas multiplot

我正在為每個月創建一個帶有 GeoPandas GeoDataFrame.plot()子圖的多圖。 如何為所有子圖使用通用圖例以及 x 和 y 軸並控制 figsize?。

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

plt.figure(sharex=True, sharey=True)返回TypeError: __init__() got an unexpected keyword argument 'sharex' 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()

在此處輸入圖片說明

@ImportanceOfBeingErnest 在上面的評論中已經解釋了shared_xshare_y關鍵字。 效果很好,如果您實際上是在展示整個世界,我會親自刪除所有刻度/標簽。 但是對於子集,它可能會有所幫助。

創建一個共享的圖例(Matplotlib 稱之為顏色條,而不是圖例)有點挑剔,因為 Geopandas 不返回軸而不是可映射的(就像 Matplotlib 通常那樣)。 一個簡單的解決方法是從軸集合中獲取它,但這確實需要一些假設,如果有多個,您需要哪個可映射。

在這種情況下,每個軸只有 1 個(補丁集合),並且每個軸都相同。 因此,使用axs[0].collections[0]獲取 ith 很簡單,但不是最強大的解決方案。

另一種方法是使用cax=cax關鍵字預先創建cax並將其提供給 Geopandas 圖。 但是手動創建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)

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM