Reputation: 253
Shown below is the syntax used to get the bar char for a categorical data on seaborn
import seaborn as sn
import matplotlib as mpl
import matplotlib.pyplot as plt
IN: data['coast'].dtypes
OUT:
CategoricalDtype(categories=[0, 1], ordered=False)
IN: data['coast'].value_counts()
OUT:
0 21450
1 163
Name: coast, dtype: int64
IN: sn.factorplot('coast', data=data, kind='count')
OUT:
Upvotes: 7
Views: 14460
Reputation: 41397
sns.barplot
with a custom percentage estimatorax.bar_label
and its fmt
paramax = sns.barplot(x='coast', y='coast', estimator=lambda x: len(x) / len(data) * 100, data=data)
ax.bar_label(ax.containers[0], fmt='%.f%%')
ax.set_ylabel('%')
Save the axes handle from sns.countplot
and use the new ax.bar_label
:
ax = sns.countplot(x='coast', data=data)
ax.bar_label(ax.containers[0])
Or for the facet-based sns.catplot
(formerly sns.factorplot
), extract the axes from the facet grid before using ax.bar_label
:
grid = sns.catplot(x='coast', kind='count', data=data)
ax = grid.axes[0, 0]
ax.bar_label(ax.containers[0])
Upvotes: 13
Reputation: 4827
Maybe this will work for you:
# imports
import sys # for retreiving package version matplotlib
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# package versions
print('numpy :', np.__version__)
print('pandas :', pd.__version__)
print('matplotlib :', sys.modules['matplotlib'].__version__)
print('seaborn :', np.__version__)
# set seed for reproducibility
np.random.seed(100)
# generate data
n = 15
data = pd.DataFrame({'coast': np.random.randint(low=0, high=2, size=n, dtype=int)})
data['coast'] = data['coast'].astype('category')
# plot data
ax = sns.countplot(x='coast', data=data)
plt.bar_label(ax.containers[0]) # plot bar labels
plt.show()
Results:
numpy : 1.21.0
pandas : 1.3.0
matplotlib : 3.4.2
seaborn : 1.21.0
Upvotes: 0