tahmid0945
tahmid0945

Reputation: 95

How to plot multiple map of geopandas dataframe?

I have a list of geometry features which I want to visualize side by side as subplots. When I type:

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

A list of 40 maps appear one after another in a list. But I want to arrange them in a 5*8 row-column arrangement. When I try to give a size of the arrangement like:

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

I get the error message:

enter image description here

Please help.

Upvotes: 0

Views: 2266

Answers (2)

swatchai
swatchai

Reputation: 18822

Since I don't have access to your dataframe, I will use the builtin naturalearth_lowres to plot an array of selected countries. Read the comments within the code for clarification of important steps.

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

The resulting plot:

enter image description here

Upvotes: 1

r-beginners
r-beginners

Reputation: 35265

I solved the issue with the official reference. Without the trim_axs() function here, 'numpy.ndrray' occurs.

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)

enter image description here

Upvotes: 1

Related Questions