Reputation: 183
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!
Upvotes: 10
Views: 19257
Reputation: 780
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
Upvotes: 9
Reputation: 182
After posting my answer, I realized I answered the opposite of what was being asked. I found this question while trying to figure out how to remove the space between bars. I almost deleted my answer, but in case anyone else stumbles on this question and is trying to remove the space between bars in seaborn's histplot, I'll leave it for now.
Thanks to @miro for Seaborn's updated documentation, I found that element='step'
worked for me. Depending on exactly what you want, element='poly'
may be what you are after.
My implementation with 'step':
fig,axs = plt.subplots(4,2,figsize=(10,10))
i,j = 0,0
for col in cols:
sns.histplot(df[col],ax=axs[i,j],bins=100,element='step')
axs[i,j].set(title="",ylabel='Frequency',xlabel=labels[col])
i+=1
if i == 4:
i = 0
j+=1
My implementation with 'poly':
fig,axs = plt.subplots(4,2,figsize=(10,10))
i,j = 0,0
for col in cols:
sns.histplot(df[col],ax=axs[i,j],bins=100,element='poly')
axs[i,j].set(title="",ylabel='Frequency',xlabel=labels[col])
i+=1
if i == 4:
i = 0
j+=1
Upvotes: 0
Reputation: 339230
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()
Upvotes: 16