Search code examples
pythonmatplotlibsubplot

Tight subplot axes without their plot to the figure


I have made a subplot in matplotlib and managed to to put the different cmap I have on the same column. For a minimal working example (with dummy cmaps):

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
data1 = np.random.rand(10, 10)
data2 = np.random.rand(10, 10)
data3 = np.random.rand(10, 10)

fig_bandwidth = plt.figure(figsize=(12, 6))
ax1 = plt.subplot(3, 2, 6)
ax2 = plt.subplot(3, 2, 4)
ax3 = plt.subplot(3, 2, 2)
ax_bandwidth = plt.subplot(1, 3, 1)
axes = [ax1, ax2, ax3]

# Plot data and add color bars
for ax, data in zip(axes, [data1, data2, data3]):
    cax = ax_bandwidth.imshow(data, aspect='auto', cmap='viridis')
    plt.colorbar(cax, ax=ax)
    ax.axis('off')
plt.tight_layout()
plt.show()

enter image description here

What I am trying to do is have a tight subplot with the figure on the left and the 3 color bars on the right in the same column, but it seems the plotting boxes are still there, preventing me from placing these axes next to the figure. Maybe using subplots isn't the best solution, any suggestion?

Then how could I place an ax title spanning across the three color bars since they represent the same thing (bandwidth in MHz for context).


Solution

  • Using add_axes works much better than sublots. It gives me much more freedom on the placement.

    Here is a minimal working example with dummy cbars:

    fig_bandwidth = plt.figure(figsize=(12, 6))
    # Creating three axes: add_axes([xmin,ymin,dx,dy])
    ax1 = fig_bandwidth.add_axes((0.75, 0.05, 0.1, 0.3))
    ax2 = fig_bandwidth.add_axes((0.75, 0.36, 0.1, 0.3))
    ax3 = fig_bandwidth.add_axes((0.75, 0.67, 0.1, 0.3))
    ax_bandwidth = fig_bandwidth.add_axes((0.1, 0.05, 0.7, 0.92))
    axes = [ax1, ax2, ax3]
    # Generate sample data
    data1 = np.random.rand(10, 10)
    data2 = np.random.rand(10, 10)
    data3 = np.random.rand(10, 10)
    for ax, data in zip(axes, [data1, data2, data3]):
        cax = ax_bandwidth.imshow(data, aspect='auto', cmap='viridis')
        plt.colorbar(cax, ax=ax)
        ax.axis('off')
    plt.show()