Search code examples
pythonpython-3.xmatplotlibjupyter-notebookjupyter

How to relax Matplotlib plot dimensions in Jupyter Notebook


I want to compare two images using matplotlib in python. My code works but I want to resize the images to be the height of the colorbars.

plt.subplot(1, 2, 1)
plt.imshow(train_images[0])
plt.colorbar()
plt.subplot(1, 2, 2)
plt.imshow(train_images_prep[0])
plt.colorbar()

enter image description here


Solution

  • Using imshow makes the axis scaling to be equal in both dimensions, resulting in a square for your image. The height of the colorbar is the same as the height of the original axis before this rescaling. Instead of using the default figure size, you may start with a wider canvas to get the desired result:

    plt.figure(figsize=(12,5))  # Dimensions in inches, play with the width
    

    Play with the dimensions as required. I would also suggest using the object-oriented API instead:

    fig, axes = plt.subplots(2, 1, figsize=(12,5))
    first = axes[0].imshow(train_images[0])
    second = axes[1].imshow(train_images_prep[0])
    fig.colorbar(first, ax=axes[0])
    fig.colorbar(second, ax=axes[1])