1
votes

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:

enter image description here

  1. How can I get the value count on the bar chart shown below. enter image description here

  2. How to get the percentage value on the bar chart shown below. enter image description here

2
What version of matplotlib do you have?BigBen
@BigBen version 3.4.1WF30
@BigBen it didn't help my need :( hope you will be a give me a solution :)WF30

2 Answers

1
votes

Percentage counts

ax = 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('%')


Regular counts

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])

0
votes

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

enter image description here