Okay, let's break down why the axis is "messed up" for your last plot and how to fix it.
The Problem:
You are mixing two different ways of managing subplots in a way that causes conflict:
plt.subplots(3, 2): This creates a grid of 6 individual Axes objects (axs[0] through axs[5]) within a single figure. You correctly use axs[0] and axs[1] for your first two plots.
plt.subplot(3, 2, (3,6)): This command tells Matplotlib to select or create a subplot in a 3x2 grid using 1-based indexing for the subplot position. The index (3,6) is causing the problem. In the context of plt.subplot(nrows, ncols, index), the index should typically be a single integer (1-based) specifying a cell, or sometimes a slice or tuple defining a range of cells if used with GridSpec. Directly providing a tuple like (3,6) as the index argument in plt.subplot(3, 2, ...) is generally not the correct way to specify a spanned area using standard plt.subplot.
The confusion arises because plt.subplot tries to create a new axis object at the specified grid location, potentially conflicting with the axis objects that were already created by plt.subplots for those locations (specifically axs[4] and axs[5], which correspond to the bottom row positions in the 0-based axs array and 1-based plt.subplot positions 5 and 6). Matplotlib gets confused about the layout and which axes object to use when you call plotting functions (plt.scatter, plt.title, etc.) after the conflicting plt.subplot call.
The Solution:
The standard and clean way to create a complex subplot layout, especially one involving spanned rows or columns, is to use matplotlib.gridspec.GridSpec. This allows you to define the overall grid structure and then use slices of that grid to place your axes objects.
Here's how you can rewrite your plotting code using GridSpec:
import matplotlib.pyplot as plt
from matplotlib.gridspec import GridSpec # Import GridSpec
# Assume train_pareto_front, test_pareto_front, trees, METRIC, etc. are defined
# (Add dummy data if you need to run this standalone)
# Example Dummy Data (replace with your actual data):
# METRIC = 'acc_blend'
# ModelResult = lambda c, m, tm, d: type('ModelResult', (object,), {'cost': c, METRIC: m, f'test_{METRIC}': tm, 'depth': d})()
# train_pareto_front = [(ModelResult(10, 0.8, 0.78, 1), None), (ModelResult(20, 0.85, 0.82, 2)), (ModelResult(30, 0.9, 0.85, 3))]
# test_pareto_front = [(ModelResult(15, 0.79, 0.8, 1), None), (ModelResult(25, 0.84, 0.86, 2)), (ModelResult(35, 0.88, 0.89, 3))]
# trees = [(ModelResult(5, 0.7, 0.65, 1), None), (ModelResult(12, 0.82, 0.75, 2)), (ModelResult(22, 0.88, 0.8, 3)), (ModelResult(32, 0.92, 0.83, 4)),
# (ModelResult(18, 0.8, 0.83, 2), None), (ModelResult(28, 0.87, 0.88, 3))]
# trees.extend(train_pareto_front) # Add pareto points to 'all'
# trees.extend(test_pareto_front)
# import numpy as np # Add noise and more points for scattering
# np.random.seed(42)
# trees.extend([(ModelResult(np.random.rand()*40+5, t[0][METRIC]+np.random.randn()*0.03, t[0][f'test_{METRIC}']+np.random.randn()*0.04, t[0]['depth']), None) for t in trees for _ in range(5)])
# END Dummy Data
fig = plt.figure(figsize=(17, 20)) # Create the figure first
# Define the grid structure: 3 rows, 2 columns
gs = GridSpec(3, 2, figure=fig)
# Create the axes using slices of the GridSpec
ax0 = fig.add_subplot(gs[0, 0]) # Top-left cell
ax1 = fig.add_subplot(gs[0, 1]) # Top-right cell
# gs[1, 0] and gs[1, 1] correspond to the middle row, which will be empty space based on your original code structure
ax_bottom_span = fig.add_subplot(gs[2, :]) # Bottom row, spanning both columns (gs[2, 0] and gs[2, 1])
tt = [('train', train_pareto_front), ('test', test_pareto_front), ('all', trees)]
costs = {k: [m['cost'] for m, _ in pf] for k, pf in tt}
train_metrics = {k: [m[METRIC] for m, _ in pf] for k, pf in tt}
test_metrics = {k: [m.get(f'test_{METRIC}') for m, _ in pf] for k, pf in tt}
colors = {'train': 'blue', 'test': 'orange', 'all': 'gray'}
# Plot 1: Cost vs Train Metric (using ax0)
for k in ['all', 'train', 'test']:
sz = 1 if k=='all' else 20
ax0.scatter(costs[k], train_metrics[k], alpha=0.5, label=k, s=sz, color=colors[k])
ax0.legend()
ax0.set_title('Train data metric with pareto fronts')
ax0.set_xlabel('Cost/1000 samples')
ax0.set_ylabel(METRIC)
# Plot 2: Cost vs Test Metric (using ax1)
for k in ['all', 'train', 'test']:
sz = 1 if k=='all' else 20
ax1.scatter(costs[k], test_metrics[k], alpha=0.5, label=k, s=sz, color=colors[k])
ax1.legend()
ax1.set_title('Test data metric with pareto fronts')
ax1.set_xlabel('Cost/1000 samples')
ax1.set_ylabel(f'test_{METRIC}')
# Plot 3: Train vs Test Metric (using ax_bottom_span)
# Ensure depth key exists for all points or handle missing keys
color = [
{1:'green', 2:'yellow', 3:'orange', 4:'red'}.get(m.get('depth', 0), 'gray') # Use get for safety, default to gray
for m, _ in trees
]
ax_bottom_span.scatter([m.get(METRIC) for m, _ in trees], [m.get(f'test_{METRIC}') for m, _ in trees],
alpha=0.5, label='all', s=1, color=color)
# You can add the pareto fronts to this plot too if desired, plotting on ax_bottom_span
# ax_bottom_span.scatter([m.get(METRIC) for m, _ in train_pareto_front], [m.get(f'test_{METRIC}') for m, _ in train_pareto_front], alpha=0.5, label='train', s=20, color='blue')
# ax_bottom_span.scatter([m.get(METRIC) for m, _ in test_pareto_front], [m.get(f'test_{METRIC}') for m, _ in test_pareto_front], alpha=0.5, label='test', s=20, color='orange')
# ax_bottom_span.legend() # Add legend if you uncomment the pareto front lines
ax_bottom_span.set_title('Train vs Test Acc')
ax_bottom_span.set_xlabel(METRIC)
ax_bottom_span.set_ylabel(f'test_{METRIC}')
# Optional: Add an empty axis for the middle row to maintain the 3x2 structure visually, though not strictly needed if you don't plot there
# fig.add_subplot(gs[1, 0]) # Empty middle-left
# fig.add_subplot(gs[1, 1]) # Empty middle-right
plt.tight_layout() # Adjust spacing between subplots
plt.show()