Increasing space between bins in seaborn distplot

10,463

Solution 1

The matplotlib hist function has an argument rwidth

rwidth : scalar or None, optional
The relative width of the bars as a fraction of the bin width.

You can use this inside the distplot via the hist_kws argument.

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

x = np.random.normal(0.5,0.2,1600)

ax = sns.distplot(x,bins=34, kde=False, 
                  hist_kws={"rwidth":0.75,'edgecolor':'black', 'alpha':1.0})

plt.show()

hist_kws

Solution 2

for Seaborn >= 0.11, use shrink parameter. It scales the width of each bar relative to the binwidth by this parameter. The rest will be empty space.

Documentation: https://seaborn.pydata.org/generated/seaborn.histplot.html

edit: OP was originally asking about sns.distplot(), however, it is deprecated in favor of sns.histplot or sns.displot() in the current version >=0.11. Since OP is generating a histogram, both histplot and displot in hist mode will take shrink

Share:
10,463
Admin
Author by

Admin

Updated on July 28, 2022

Comments

  • Admin
    Admin almost 2 years

    So I have this, probably, simple question. I created a histogram from data out of an excel file with seaborn. Forbetter visualization, I would like to have some space between the bars/bins. Is that possible?

    My code looks as followed

    import pandas as pd
    import matplotlib as mpl
    import matplotlib.pyplot as plt
    import numpy as np
    import seaborn as sns
    
    %matplotlib inline
    from IPython.display import set_matplotlib_formats
    set_matplotlib_formats('svg', 'pdf')
    
    
    df = pd.read_excel('test.xlsx')
    sns.set_style("white")
    #sns.set_style("dark")
    plt.figure(figsize=(12,10))
    plt.xlabel('a', fontsize=18)
    plt.ylabel('test2', fontsize=18)
    
    plt.title ('tests ^2', fontsize=22)
    
    
    ax = sns.distplot(st,bins=34, kde=False, hist_kws={'range':(0,1), 'edgecolor':'black', 'alpha':1.0}, axlabel='test1')
    

    A second question though a bit off topic would be, how I get the exponent in the title of the chart to actually be uplifted?

    Thanks!

  • MERose
    MERose over 3 years
    Doesn't work with seaborn >= 0.11 any more, unfortunately. distplot() became displot() or histplot(), and neither passes on the rwidth parameter.
  • PatrickT
    PatrickT over 2 years
    2022: The hist_kws argument is available for sns.distplot(), but not for sns.histplot().
  • PatrickT
    PatrickT over 2 years
    The OP is asking about sns.displot(), while sns.histplot() takes different arguments.
  • PatrickT
    PatrickT over 2 years
    The OP is asking about sns.distplot() not sns.histplot(). As it turns out, they are quite different.
  • miro
    miro over 2 years
    @PatrickT thanks for noticing, I have improved the answer.
  • PatrickT
    PatrickT over 2 years
    upvote from me. :-)