3

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'
tdy
  • 36,675
  • 19
  • 86
  • 83
nigel yaso
  • 33
  • 4
  • 2
    Your last line clearly indicates why your code does not work: `countplot()` does not have a parameter `estimator` that you can give to it. In order to display your count as percentages, you can have a look at https://stackoverflow.com/questions/34615854/seaborn-countplot-with-normalized-y-axis-per-group – Steven Robyns Feb 27 '22 at 09:26

1 Answers1

2

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

JohanC
  • 71,591
  • 8
  • 33
  • 66
  • Thanks a lot, was using this marketing analysis data https://github.com/Kaushik-Varma/Marketing_Data_Analysis – nigel yaso Feb 28 '22 at 20:19