Chris
Chris

Reputation: 2071

Modifying subplots sizes

I have been trying to find some answers, but most of them don't include a table, or they solve the problem generally and I get in trouble trying to find a workaround with the table I created as I managed to put the table through an empty axis. But now decreasing the right-axis size (as the table gets accommodated to the axis size) and increasing the left two-axis size is becoming a daunting task.

I have this code:

fig = plt.figure(figsize=(18,5))
ax1 = fig.add_subplot(221)
ax2 = fig.add_subplot(223)
ax3 = fig.add_subplot(122)
ax3.axis('off')
data = pd.DataFrame({'metrics': ['MSLE train', 'msle_test', 'asdsad'],
              'values': [0.43, 0.52, 0.54]})
ax3.table(cellText=data.values, colLabels=data.columns, loc='center')


fig.suptitle(f'Train MSLE: {msle_train}, Test MSLE: {msle_test}') 
ax1 = y_data.plot(label='Original data', ax=ax1, c='blue')
ax1 = y_pred_train.plot(ax=ax1, c='orange')
ax1 = y_pred_test.plot(ax=ax1, c='orange', linestyle='--')
ax1.legend()

ax2 = error_train.plot(label='Train error', ax=ax2)
ax2 = error_test.plot(label='Test error', ax=ax2, linestyle='--')
ax2.legend()
    
plt.show()

That returns this plot:

enter image description here

I'm looking to increase the horizontal size of the two left plots, something near the red mark:

enter image description here

Any suggestions?

Upvotes: 2

Views: 67

Answers (1)

MagnusO_O
MagnusO_O

Reputation: 1283

You can use gridspec.
It even works with a vertical centered right hand side and a table:

import matplotlib.pyplot as plt
from matplotlib import gridspec
import pandas as pd

data = pd.DataFrame({'metrics': ['MSLE train', 'msle_test', 'asdsad'],
          'values': [0.43, 0.52, 0.54]})

fig = plt.figure(figsize=(18,5))

gs = gridspec.GridSpec(4, 2, width_ratios=[3,1]) 
ax1 = fig.add_subplot(gs[0:2,:-1])
ax1.set_title('ax1')
ax2 = fig.add_subplot(gs[2:4,:-1])
ax2.set_title('ax2')
ax3 = fig.add_subplot(gs[1:3,1])
ax3.set_axis_off()
ax3.table(cellText=data.values, colLabels=data.columns, loc='center')

fig.tight_layout() 
plt.show()

enter image description here

Notes:

  • Horizontal alignment is set with the ratio of width_ratios=[3,1]
  • fig.tight_layout() is helpfull to automatically align the spacing between the plots.
  • Vertical centering is achieved with a little workaround by having initially a larger vertical grid than required (no. of vertical plots) and distributing the plots and table accordingly (see e.g. gs[2:4).
  • The titles were just added for visual orientation.
  • ax3.set_axis_off() is required to suppress the plot frame at the table position - without it you'll get: enter image description here

Upvotes: 3

Related Questions