Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas: seaborn countplot from several columns

I have a dataframe with several categorical columns. I know how to do countplot which routinly plots ONE column. Q: how to plot maximum count from ALL columns in one plot?

here is an exemplary dataframe to clarify the question:

import pandas as pd
import numpy as np
import seaborn as sns

testdf=pd.DataFrame(({   'Ahome' :   pd.Categorical(["home"]*10),
                         'Bsearch' : pd.Categorical(["search"]*8 + ["NO"]*2),
                          'Cbuy' : pd.Categorical(["buy"]*5 + ["NO"]*5),
                          'Dcheck' : pd.Categorical(["check"]*3 + ["NO"]*7),


                     } ))
testdf.head(10)
sns.countplot(data=testdf,x='Bsearch');

The last line is just using normal countplot for one column. I'd like to have the columns category (home,search,buy and check) in x-axis and their frequency in y-axis.

Thanks in advance!

like image 582
physiker Avatar asked Jul 06 '18 13:07

physiker


People also ask

How do you plot multiple columns in Seaborn?

In Seaborn, we will plot multiple graphs in a single window in two ways. First with the help of Facetgrid() function and other by implicit with the help of matplotlib. data: Tidy dataframe where each column is a variable and each row is an observation.

Can SNS Countplot () be used to see the frequency distribution of a categorical variable?

Show the counts of observations in each categorical bin using bars. A count plot can be thought of as a histogram across a categorical, instead of quantitative, variable.

How do you use Countplot in Seaborn?

To create a horizontal bar chart or countplot in Seaborn, you simply map your categorical variable to the y-axis (instead of the x-axis). When you map the categorical variable to the y-axis, Seaborn will automatically create a horizontal countplot.


1 Answers

You need to use countplot as below:

df = pd.melt(testdf)
sns.countplot(data=df.loc[df['value']!="NO"], x='variable', hue='value')

Output:

enter image description here

like image 136
harvpan Avatar answered Oct 01 '22 15:10

harvpan