I do generate that figure with seaborn.distplot()
. My problem is that the ticks on the X-axis do not fit to the bars, in all cases. I would expect a relationship between bars and ticks like you can see at 11 and 15.
This is the MWE
import numpy as np
import pandas as pd
import seaborn as sns
# Data
np.random.seed(42)
n = 5000
df = pd.DataFrame({
'PERSON': np.random.randint(100000, 999999, n),
'Fruit': np.random.choice(['Banana', 'Strawberry'], n),
'Age': np.random.randint(9, 18, n)
})
fig = sns.displot(
data=df,
x='Age',
hue='Fruit',
multiple='dodge').figure
fig.show()
You need discrete=True
to tell seaborn that the x values are discrete. Adding shrink=0.8
will leave some space between the bars.
import numpy as np
import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt
# Data
np.random.seed(42)
n = 5000
df = pd.DataFrame({
'PERSON': np.random.randint(100000, 999999, n),
'Fruit': np.random.choice(['Banana', 'Strawberry'], n),
'Age': np.random.randint(9, 18, n)
})
sns.displot(
data=df,
x='Age',
hue='Fruit',
multiple='dodge',
discrete=True,
shrink=0.8)
plt.show()
.
Note that
sns.displot()
is a figure-level function that creates a grid of one or more subplots, with a common legend outside. sns.countplot()
is an axes-level function, that creates a single subplot with a legend inside.
An alternative is creating a countplot
:
sns.countplot(
data=df,
x='Age',
hue='Fruit',
dodge=True
)