【发布时间】:2020-03-04 17:49:48
【问题描述】:
我正在为每个月创建一个带有 GeoPandas GeoDataFrame.plot() 子图的多图。如何为所有子图共用图例以及 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()
【问题讨论】:
-
sharex和sharey可以用作plt.subplots、fig, ax_array = plt.subplots(4,3, sharex=True, sharey=True)的参数。但是,这不会创建共享图例。 -
它也对我不起作用。
ax = plt.subplot(4, 3, index + 1, sharex=True, sharey=True)yielsTypeError: cannot create weak reference to 'bool' object. -
是的,因为我说
plt.subplots -
感谢您的支持。但是,将
ax = plt.subplot(4, 3, index + 1)替换为fig, ax_array = plt.subplots(4,3, sharex=True, sharey=True)或fig, ax_array = plt.subplots(4,3, index + 1, sharex=True, sharey=True)会分别导致空白画布和TypeError: subplots() got multiple values for argument 'sharex'。 -
这需要在循环之外,随后您需要在
ax_array内的轴上循环。但如前所述,这只是为了显示您的错误来自哪里,它不会创建任何共享图例或类似内容。
标签: python matplotlib geopandas