python - GeoPandas 多图中的共享图例
问题描述
GeoDataFrame.plot()
我正在为每个月创建一个带有 GeoPandas子图的多图。如何为所有子图共用图例以及 x 和 y 轴并控制 figsize?
我知道有sharex=True
,sharey=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()
解决方案
@ImportanceOfBeingErnest 在上面的评论中已经解释了shared_x
and关键字。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)
推荐阅读
- firefox - 在 Mozilla Firebox PIV 证书未选择
- excel - Excel 损坏并进入只读模式
- python - 使用 Python 打开 Access 数据库
- python - TemplateDoesNotExist at /hobbies/(已解决)
- mongoose - 如何使用数据库连接到我们的模式
- sql - 最近 N 天总和的前 5 个名字
- mysql - Laravel Docker 容器无法连接到远程 AWS RDS 数据库
- sql - 如何在引用同一个表的两个列上删除级联?
- excel - 在 Excel 中使用 IF 语句进行数据验证
- google-apps-script - 使用脚本将公式添加到谷歌工作表时无法识别的功能