Search code examples
pythonpandasmatplotlibhistogramhistogram2d

Decrease white space among bars in Matplotlib histograms


I generated the following histogram: enter image description here

I wish to compact the histogram, i.e. reducing the white space between bars (for instance, between 0.8-0.85 and 0.85-0.9).

In this respect, a solution that increase the width of the bars is not convenient for me.

All the already asked question I found, at best of my knowledge, explain how to reduce the external white space (i.e., after 0.95-1 and before 0.75-0.8).

The code I used to generate the histogram is:

import pandas as pd
import numpy as np
from matplotlib import pyplot as plt

dataset = pd.read_csv('compare.csv', usecols=['Y', 'X'])

dict = {'0.75-0.8': [0, 0], '0.8-0.85': [0, 0], '0.85-0.9': [0, 0], '0.9-0.95': [0, 0], '0.95-1': [0, 0]}

mylist = list(dict.values())
#various code that fills 'mylist'    

df = pd.DataFrame(data=mylist,
                 index=['0.75-0.8', '0.8-0.85', '0.85-0.9', '0.9-0.95', '0.95-1'],
                 columns=pd.Index(['Y', 'X'],
                 )).round(2)

ax = pd.DataFrame(df).plot.bar(color=("dodgerblue", "pink"), legend=True, figsize=(8, 6))
for container, hatch in zip(ax.containers, ("", "//")):
    for patch in container.patches:
        patch.set_hatch(hatch)
plt.show()

Solution

  • change this line with

    ax = pd.DataFrame(df).plot.bar(color=("dodgerblue", "pink"), legend=True, figsize=(8, 6))
    

    with this line

    ax = df.plot(kind='bar', width=0.9, color=("dodgerblue", "pink"), legend=True, figsize=(8, 6))
    

    and adjust the value width to your liking

    enter image description here