3

I am trying to generate a histogram from a DataFrame with seaborn enabled via the DataFrame.hist method, but I keep finding extra space added to either side of the histogram itself, as seen by the red arrows in the below picture: Histogram with additional spacing

How can I remove these spaces? Code to reproduce this graph is as follows:

import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

from random import seed, choice
seed(0)

df = pd.DataFrame([choice(range(250)) for _ in range(100)], columns=['Values'])

bins = np.arange(0, 260, 10)

df['Values'].hist(bins=bins)
plt.tight_layout()
plt.show()
asongtoruin
  • 9,794
  • 3
  • 36
  • 47

1 Answers1

7

plt.tight_layout() only has an effect for the "outer margins" of your plot (tick marks, ax labels etc.).

By default matplotlib's hist leaves an inner margin around the hist bar-plot. To disable you can do this:

ax = df['Values'].hist(bins=bins)
ax.margins(x=0)
plt.show()
Jörn Hees
  • 3,338
  • 22
  • 44
  • This does indeed remove the spaces! Thankyou. I'll leave the question for a little longer to see if there are any further explanations as to why this happens, and mark yours as the answer if none appears. – asongtoruin Aug 25 '17 at 12:06
  • 1
    Using `xlim` requires to know or determine the desired limits. A better solution is surely to use `ax.margins(x=0)` as in [the duplicate](https://stackoverflow.com/questions/42045767/how-can-i-change-the-x-axis-in-matplotlib-so-there-is-no-white-space). – ImportanceOfBeingErnest Aug 25 '17 at 12:28
  • indeed, updated to include this cleaner solution – Jörn Hees Aug 25 '17 at 12:39
  • @ImportanceOfBeingErnest you're right - apologies for missing the dupe, too. – asongtoruin Aug 25 '17 at 13:01