0
$\begingroup$

df in my program happens to be a dataframe with these columns :

df.columns
'''output : Index(['lat', 'lng', 'desc', 'zip', 'title', 'timeStamp', 'twp', 'addr', 'e',
'reason'],
 dtype='object')'''

When I execute this piece of code:

sns.countplot(x = df['reason'], data=df)
# output is the plot below

countplot 1

but if i slightly tweak my code like this :

p = df['reason'].value_counts()
k = pd.DataFrame({'causes':p.index,'freq':p.values})
sns.countplot(x = k['causes'], data = k)

countplot 2

So essentially I just stored the 'reasons' column values and its frequencies as a series in p and then converted them to another dataframe k but this new countplot doesn't have the right range of Y-axis for the given values.

My doubts happen to be :

  • Can we set of Y-axis in the second countplot in its appropriate limits
  • Why the does second countplot differ from the first one when i just separated the specific column i wanted to graph and plotted it separately ?
$\endgroup$
1
$\begingroup$

Countplot from seaborn will not work as you expect. When you calculate the frequencies, you want to plot the values in p.values as they appear. Countplot will take a dataframe where labels are not aggregated and then count each one of them, as it did in the first case.

So countplot will be appropriate for the case where your dataframe looks like:

index | reason |
0        EMS
1        EMS
2        Traffic
3        Fire
4        Fire
5        EMS
6        Traffic
...

In the second case you already have your frequencies:

index | reason |
EMS       10
Traffic   21 
Fire      15

Then count plot will just count the lines and it will be one for each, that is why your plot looks like that.

To solve your problem you could just plot using .plot from pandas:

df['reason'].value_counts(normalize=True).plot(kind='bar')

Where the parameter normalize=True will show normalized frequencies instead of raw count values.

$\endgroup$
  • $\begingroup$ wow I had never thought that way, so countplot counts the lines only $\endgroup$ – Arnav Das Mar 10 at 13:35
  • 1
    $\begingroup$ Yes, thats right. So in the second case you should use barplot only. $\endgroup$ – Victor Oliveira Mar 10 at 13:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.