1

I need to add a grayscale image and its histogram to a figure. The two subplots should be the same size, but the histogram is displayed twice as high as the image. How can I make both subplots to have the same height?

Here's my code:

import numpy as np
from skimage import io
import matplotlib.pyplot as plt

L = 256
img = io.imread('https://i.stack.imgur.com/ywPGr.png')
edges = np.arange(L+1)
hist, _ = np.histogram(img, bins=edges)
centers = edges[:-1]

fig, [ax1, ax2] = plt.subplots(1, 2)
ax1.imshow(img, cmap=plt.cm.gray)
ax1.axis('off')
ax2.fill_between(centers, hist)
fig.tight_layout()
plt.show(fig)

Image and histogram

I've tried the solutions proposed in the accepted answer to this similar question, but none of them worked for me.

Using automatic aspect on the image changes its aspect ratio (which is not acceptable):

ax1.imshow(img, cmap=plt.cm.gray, aspect='auto')

First workaround

Adding these two lines does not yield the desired result either:

asp = np.diff(ax2.get_xlim())[0] / np.diff(ax2.get_ylim())[0]
ax2.set_aspect(asp)

Second workaround

Tonechas
  • 13,398
  • 16
  • 46
  • 80
  • Try adding a background color to the image. Thats what I usually do – AlanSTACK Feb 16 '18 at 00:43
  • 1
    Try to change: `fig, [ax1, ax2] = plt.subplots(1, 2, figsize=(12,6))`. The problem with your current plot is that the plot region height is too large and this is leaving empty place in your left image. – TYZ Feb 16 '18 at 00:45
  • Sorry, my answer to the linked question is only valid for square images. I will update it shortly. – ImportanceOfBeingErnest Feb 16 '18 at 00:45
  • Ok, done, see last paragraph of my answer to the linked question. I guess we can again close as dupe. Just mind that you have to set the aspect **after** drawing the `fill_between` curve, else you get that small line as shown in your last image here. – ImportanceOfBeingErnest Feb 16 '18 at 00:50
  • 1
    Thank you @Yilun Zhang, `figsize=(16,6)` did the trick. If you post this workaround as an aswer I will be pleased to accept it. – Tonechas Feb 16 '18 at 00:51

0 Answers0