How to specify subplots layout with gridspec

100 views Asked by At

I'm trying to use plt.GridSpec() to set up two subplots such that the left one takes up about 67% of the space and the right one takes up 33%.

I looked at the documentation, but I just can't seem to figure out how to set up the indexing--probably due a lack of experience with numpy slicing.

Repeatable Example

%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd


## Dummy Data
x = [0, 0.03, 0.075, 0.108, 0.16, 0.26, 0.37, 0.49, 0.76, 1.05, 1.64,
    0.015, 0.04, 0.085, 0.11, 0.165, 0.29, 0.37, 0.6, 0.78, 1.1]
y = [16.13, 0.62, 2.15, 41.083, 59.97, 13.30, 7.36, 6.80, 4.97, 3.53, 11.77,
    30.21, 64.47, 57.64, 56.83, 46.69, 4.22, 30.35, 35.12, 5.22, 25.32]
label = ['blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue', 'blue',
        'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red', 'red']

df = pd.DataFrame(
    list(zip(x, y, label)), 
    columns =['x', 'y', 'label']
    ) 

## Plotting
fig = plt.figure(figsize=([10,8]))
grid = plt.GridSpec(1, 3, wspace=0.4, hspace=0.3)
ax1 = plt.subplot(grid[0, :1])
ax2 = plt.subplot(grid[0, 2], sharey = ax1)

ax1.scatter(x=df.y, y=df.x, color=df.label)

df_red = df[df['label'] == "red"]
df_blue = df[df['label'] == "blue"]
myhist = ax2.hist([df_blue.x, df_red.x],
         density=False,
         edgecolor='black',
         color=['blue', 'red'],
         cumulative=False,
         bins='auto',
         orientation='horizontal',
         stacked=True,
         label=['Blue', 'Red'])

ax1.set_xlabel('length')
ax1.set_ylabel('value')
ax2.set_xlabel('frequency')
ax2.set_ylabel('value')

Current Result enter image description here

Desired Result
Same plot, just with the left:right ratio at 67% : 33% (so left plot is wider than right plot).

1

There are 1 answers

0
Sameeresque On BEST ANSWER

enter image description here

Here's the small modification that you need to make:

# one position less than 3rd column
ax1 = plt.subplot(grid[0, :-1])