Dushi Fdz
Dushi Fdz

Reputation: 151

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

Upvotes: 0

Views: 1936

Answers (2)

Dushi Fdz
Dushi Fdz

Reputation: 151

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

Upvotes: 1

mozway
mozway

Reputation: 260390

You can use GridSpec for multicolumn layouts. Here create a grid with 3 rows, 7 columns with width ratios [1,1,0.5,0.5,1,0.5,0.5], and plot axes in the second and third rows in the combined 0.5 columns.

gs = GridSpec(3, 7, figure=fig, width_ratios=[1,1,0.5,0.5,1,0.5,0.5])
ax_merged_top = fig.add_subplot(gs[0, 3:6])
ax_row1_pseudocol3 = fig.add_subplot(gs[1, 2:4])

Here is a full example:

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

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

ax1 = plt.subplot(gs[0,1])
ax_merged_top = plt.subplot(gs[0, 3:6])

for row in [1,2]:
    extra=0
    for col in range(5):
        if col in (2,4):
            ax = plt.subplot(gs[row,col+extra:col+extra+2])
            extra+=1
        else:
            ax = plt.subplot(gs[row,col+extra])

custom gridspec

And now you can change width_ratio to anything provided the numbers initially set as [0.5,0.5] add up to 1, example below with width_ratios=[1,1,0.3,0.7,1,0.5,0.5]

alternative width ratio

Upvotes: 1

Related Questions