Search code examples
pythonmatplotlibwidthsubplot

Is it possible to reduce the width of a single subplot in gridspec/Matplotlib?


I have a grid of subplots created using gridspec. I know how to create subplots that span rows and columns in gridspec. Is it possible to reduce the width of a single sub-plot just by a small amount? For example, can we set the width ratio for a single subplot? The way I want it is marked in red in the image.

enter image description here

My code looks like this:

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

plt.figure(figsize=(6, 4))
gs = gridspec.GridSpec(3, 5,  height_ratios=[0.5,1,1])

for i in range(1, 3):
    for j in range(5):
      ax = plt.subplot(gs[i, j])

ax1 = plt.subplot(gs[0,1:2])
ax2 = plt.subplot(gs[0,2:])

for ax in [ax1, ax2]:
    ax.tick_params(size=0)
    ax.set_xticklabels([])
    ax.set_yticklabels([])

What I tried:

I tried setting the width ratio as width_ratios = [1,1,1,1,0.5], but that reduces the width of the whole column (last column).


Solution

  • Thank you @JodyKlymak for mentioning about ax.set_postion method. @mozway provided a working solution, but adding these few lines in my code gave me the desired output:

    bb = ax2.get_position()
    bb.x1 = 0.84
    ax2.set_position(bb)
    
    bb = ax2.get_position()
    bb.x0 = 0.50
    ax2.set_position(bb)
    

    enter image description here