5

I have used this code to group by the continents and then plotted using geopandas. I would like to set the plot title for each continent. I would have liked also to draw the continents side by side.

import geopandas as gpd
import matplotlib.pyplot as plt
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))

continent = world.groupby('continent')
continent.plot()
plt.show()

1 Answer 1

7

If you want to represent the continents side by side, you have to create subplots on the same fig. To do so, you can iterate through your group of continents. Here is an example:

import geopandas as gpd
import matplotlib.pyplot as plt

world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
continent = world.groupby('continent')

plt.figure()

# Iterate through continents

for i, (continent_name, continent_gdf) in enumerate(continent):
    # create subplot axes in a 3x3 grid
    ax = plt.subplot(3, 3, i + 1) # nrows, ncols, axes position
    # plot the continent on these axes
    continent_gdf.plot(ax=ax)
    # set the title
    ax.set_title(continent_name)
    # set the aspect
    # adjustable datalim ensure that the plots have the same axes size
    ax.set_aspect('equal', adjustable='datalim')

plt.tight_layout()
plt.show()

yields

continents

6
  • Very nice! How can I adjust the figsize?
    – Stücke
    Commented Feb 14, 2020 at 15:33
  • 1
    With the figsize keyword argument. See matplotlib.org/api/_as_gen/matplotlib.pyplot.figure.html
    – Delforge
    Commented Feb 14, 2020 at 15:39
  • Thank you for your response! I've played around with it but I don't get where exactly I have to position figsize(x,y)
    – Stücke
    Commented Feb 14, 2020 at 15:42
  • If I add plt.figsize(10,5) behind the for loop I receive the following error: AttributeError: module 'matplotlib.pyplot' has no attribute 'figsize'
    – Stücke
    Commented Feb 14, 2020 at 15:44
  • Neither can I place it within ax = plt.subplot()
    – Stücke
    Commented Feb 14, 2020 at 15:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.