如何解决如何绘制Geopandas数据框的多个地图?
我有一个几何特征列表,我想将它们并排可视化为子图。当我键入:
for i in iaq:
fig,ax = plt.subplots(figsize=(8,5))
df_g2[df_g2['aq_date'] == i].plot(column='zone_id',cmap='Greens',ax=ax,legend=True)
ax.set_title('Analysis :'+ str(i))
plt.show()
40张地图的列表在列表中一个接一个地出现。但是我想以5 * 8的行列排列它们。当我尝试给出像这样的排列大小时:
fig,ax = plt.subplots(nrows=8,ncols=5)
fig.set_size_inches(6,4)
for i in iaq:
df_g2[df_g2['aq_date'] == i].plot(column='zone_id',legend=True)
ax.set_title('Analysis :'+ str(i))
plt.show()
我收到错误消息:
请帮助。
解决方法
我与官方reference解决了这个问题。如果没有trim_axs()
函数,则会出现“ numpy.ndrray”。
import numpy as np
import matplotlib.pyplot as plt
figsize = (9,9)
cols = 5
rows = 8
x = np.linspace(0,10,500)
y = np.sin(x)
def trim_axs(axs,N):
"""
Reduce *axs* to *N* Axes. All further Axes are removed from the figure.
"""
axs = axs.flat
for ax in axs[N:]:
ax.remove()
return axs[:N]
axs = plt.figure(figsize=figsize,constrained_layout=True).subplots(rows,cols)
axs = trim_axs(axs,cols*rows)
for ax,i in zip(axs,range(1,(cols*rows)+1)):
ax.set_title('Analysis :'+ str(i))
ax.plot(x,y,'o',ls='-',ms=4)
,
由于我无权访问您的数据框,因此我将使用内置的naturalearth_lowres
绘制一系列选定国家/地区。阅读代码中的注释以阐明重要步骤。
import geopandas as gpd
import matplotlib.pyplot as plt
# for demo purposes,use the builtin data
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
# set number of subplots' (columns,rows) enough to use
cols,rows = 2,3 #num of subplots <= (cols x rows)
# create figure with array of axes
fig,axs = plt.subplots(nrows=rows,ncols=cols)
fig.set_size_inches(6,10) #set it big enough for all subplots
# select some countries to plot
# number of them is intended to be less than (cols x rows)
# the remaining subplots will be discarded
iaq = ['IND','TZA','CAN','THA','BRN']
count = 0
for irow in range(axs.shape[0]):
for icol in range(axs.shape[1]):
#print(icol,irow)
if count<len(iaq):
# plot that country on current axes
world[ world['iso_a3'] == iaq[count] ].plot(ax=axs[irow][icol])
axs[irow][icol].set_title('world:iso_a3: '+iaq[count])
count +=1
else:
# hide extra axes
axs[irow][icol].set_visible(False)
plt.show()
结果图:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。