Skip to content
Advertisement

How to get the label values on a bar chat with seaborn on a categorical data

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

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement