I am trying to do categorical analysis I want to convert count values to percentage and I am getting an error

Viewed 165

My code is:

sns.countplot(x='marital', hue='loan', data=df, estimator=lambda x: sum(x==0)*100.0/len(x))

It gives the following error:

AttributeError                            Traceback (most recent call last)
<ipython-input-21-9615e7e7b899> in <module>()
----> 1 sns.countplot(x='marital', hue='loan', data=df, estimator=lambda x: sum(x==0)*100.0/len(x))

8 frames
/usr/local/lib/python3.7/dist-packages/matplotlib/artist.py in _update_property(self, k, v)
   1000                 if not callable(func):
   1001                     raise AttributeError('{!r} object has no property {!r}'
-> 1002                                          .format(type(self).__name__, k))
   1003                 return func(v)
   1004 

AttributeError: 'Rectangle' object has no property 'estimator'
1 Answers

sns.countplot doesn't support an estimator= parameter. However, you could create a bar plot to simulate a count plot. As a bar plot needs a numeric y-value, a workaround is to use an array of ones.

sns.barplot(x='marital', y=np.ones(len(df)),  hue='loan', data=df, estimator=lambda x: len(x)*100.0/len(df), ci=None)

As no data and no data types were given, here is an example using the tips data set:

import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np

tips = sns.load_dataset('tips')
sns.set()
ax = sns.barplot(x='day', y=np.ones(len(tips)), hue='smoker', data=tips, palette='autumn',
                 estimator=lambda x: len(x) * 100.0 / len(tips), ci=None)
ax.set_ylabel('Percentage of counts')
plt.show()

sns.barplot simulating countplot with percentages

Another approach would be to create a regular countplot and change the ticks:

import matplotlib.pyplot as plt
from matplotlib.ticker import PercentFormatter, MultipleLocator
import seaborn as sns
import numpy as np

tips = sns.load_dataset('tips')
sns.set()
ax = sns.countplot(x='day', hue='smoker', data=tips, palette='winter')
ax.yaxis.set_major_locator(MultipleLocator(len(tips) * 0.05))
ax.yaxis.set_major_formatter(PercentFormatter(len(tips), decimals=0))
plt.show()

sns.countplot with percentages as ticks

Related