【问题标题】:How to plot multiple map of geopandas dataframe?如何绘制 geopandas 数据框的多个地图?
【发布时间】:2021-02-13 11:33:09
【问题描述】:

我有一个几何特征列表,我想将它们并排显示为子图。当我输入时:

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', cmap='Greens', ax=ax, legend=True)
   ax.set_title('Analysis :'+ str(i))
   plt.show()

我收到错误消息:

请帮忙。

【问题讨论】:

  • 哪一行代码出现错误?我在您的代码中没有看到set_aspect()
  • @DavidErickson,对于线' df_g2[df_g2['aq_date'] == i].plot(column='zone_id', cmap='Greens', ax=ax, legend=True) ' 我得到了这个错误。你能建议任何方便的方法来绘制多个地图作为子图吗?

标签: python pandas matplotlib subplot geopandas


【解决方案1】:

由于我无权访问您的数据框,我将使用内置的 naturalearth_lowres 来绘制一组选定国家/地区。阅读代码中的 cmets 以了解重要步骤。

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()

结果图:

【讨论】:

    【解决方案2】:

    我用官方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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-06
      • 1970-01-01
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      相关资源
      最近更新 更多