0

I'd like to have a grid with 2 cols and 1 row. The first column will host a map with different countries, the second one should host a plot for each country in the map stacked vertically.

The plots should share the x axis, this I would like to use plt.subplots with sharex=True.

However, in the examples I saw (e.g. this one), they first create the grid and then add subplot to it one at a time. This way I could not use shared axis I guess. Is there a way to do it combined with a grid?

Desired output:

subplots in grid

What I tried is defining as many rows for the grid as the number of countries to plot separately on the right of my figure, without having found a way to use sharex=True.

Here is a simplified example (modified from https://towardsdatascience.com/plot-organization-in-matplotlib-your-one-stop-guide-if-you-are-reading-this-it-is-probably-f79c2dcbc801):

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

time = np.linspace(0, 10, 1000)
height = np.sin(time)
weight = time*0.3 + 2
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))

fig = plt.figure(figsize=(10, 5))
gs = gridspec.GridSpec(nrows=2, ncols=2)
ax0 = fig.add_subplot(gs[:, 0])
ax0.plot(time, height)

ax1 = fig.add_subplot(gs[0, 1])
ax1.plot(time, weight)
ax2 = fig.add_subplot(gs[1, 1])
plt.show()
umbe1987
  • 2,894
  • 6
  • 35
  • 63

1 Answers1

0

Ok, sorry, I found a solution here.

The trick is to set sharex equal to one of the x axis already created, and then hiding the x ticks explicitly for all but the lower graph (in my case).

Here is the modified code:

import matplotlib.pyplot as plt
from matplotlib import gridspec
import numpy as np

time = np.linspace(0, 10, 1000)
height = np.sin(time)
weight = time*0.3 + 2
score = time**2 + height
distribution = np.random.normal(0, 1, len(time))

fig = plt.figure(figsize=(10, 5))
gs = gridspec.GridSpec(nrows=2, ncols=2)
ax0 = fig.add_subplot(gs[:, 0])
ax0.plot(time, height)

ax1 = fig.add_subplot(gs[1, 1])
ax1.plot(time, weight)
ax2 = fig.add_subplot(gs[0, 1], sharex=ax1)
plt.setp(ax2.get_xticklabels(), visible=False)
plt.show()
umbe1987
  • 2,894
  • 6
  • 35
  • 63