8

I want a plot with two subplots, one larger with a map and second smaller with a scatter plot. I am using cartopy for plotting map. I determine the fraction of height by using gridspec_kw. However, due to projection constraints, it also affects the width.This is what i get .

This is what I get.

import matplotlib.pyplot as plt
import cartopy as ccrs
fig, ax = plt.subplots(2,1,subplot_kw=dict(projection=ccrs.crs.PlateCarree()),gridspec_kw={'height_ratios': [4, 1]})

One possible solution would be to use subplot_kw=dict(projection=ccrs.crs.PlateCarree() only for the upper panel. But i am not able to figure out how do this. There are ways which recommend add_subplot, but that is very manual and i don't like this. Is is possible to do with plt.subplots()?

This is what I want This is what I want.

rpanai
  • 12,515
  • 2
  • 42
  • 64
Vinod Kumar
  • 1,383
  • 1
  • 12
  • 26
  • 2
    No you cannot do this with subplots. – Jody Klymak Apr 26 '20 at 04:01
  • Have you tried a `(2,3)` shaped figure? with `(0,0)` position and `colspan=3` for cartopy's ax, and `(1,1)` position for scatter plot. [matplotlib grispec and others placement managers](https://matplotlib.org/1.3.1/users/gridspec.html) – david Apr 26 '20 at 11:06

1 Answers1

11

my suggestion would be to use gridspec to control the subplots size and fig.add_subplot instead of plt.subplots. That way you could specify the Cartopy projection only to the first subplot.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec
import cartopy.crs as ccrs
import cartopy.feature as cfeature

fig = plt.figure()
gs = fig.add_gridspec(3, 3)

ax1 = fig.add_subplot(gs[0:2, :], projection=ccrs.PlateCarree())
ax1.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())
ax1.coastlines(resolution='auto', color='k')
ax1.gridlines(color='lightgrey', linestyle='-', draw_labels=True)

ax2 = fig.add_subplot(gs[2, :])
ax2.plot([1, 2], [3, 4])

enter image description here

  • Thanks for answering. This would work but it was not what I was looking for. fig.add_subplot is bit difficult to work under loops. I wanted an answer using plt.subplots. But this is not possible I guess, as already pointed out in comment previously. – Vinod Kumar May 29 '20 at 07:52
  • `NameError: name 'ax' is not defined` – duff18 Jul 23 '21 at 14:06
  • You are right @duff18, it should be `ax1.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())` and not `ax.set_extent([-180, 180, -90, 90], crs=ccrs.PlateCarree())`. Fixed now. – Marcelo Andrioni Jul 23 '21 at 18:59
  • can one adjust the distance between the subplots – Xue May 11 '23 at 11:40