Bluetail
Bluetail

Reputation: 1291

Customizing a seaborn countplot with additional categorical variable

I am following the guidance from there to create a bar chart similar to the last example:

https://seaborn.pydata.org/generated/seaborn.countplot.html

however, I want to show only the survived =1 plot.

My data is very similar, and my chart looks like this (so I want to show only the right part of my chart with left =yes). enter image description here

also, what values does the order parameter take? I wish I could sort them by count. It does not take desc or descending.

Upvotes: 0

Views: 1349

Answers (1)

JohanC
JohanC

Reputation: 80509

You can use data=df[df['left']=='yes'] to just plot the right part. To order by count, you can use ... .value_counts().index for the order= parameter.

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

prob = np.random.rand(7) + 0.1
prob /= prob.sum()
df = pd.DataFrame({'department': np.random.choice(['helium', 'neon', 'argon', 'krypton', 'xenon', 'radon', 'oganesson'],
                                                  1000, p=prob),
                   'left': np.random.choice(['yes', 'no'], 1000)})
sns.set_style('white')
filter = df['left'] == 'yes'
g = sns.catplot(data=df[filter], kind='count', y='department', palette='mako_r',
            order=df[filter]['department'].value_counts(ascending=True).index)
for ax in g.axes.flat:
    ax.bar_label(ax.containers[0], fontsize=12)
    ax.margins(x=0.1)
plt.tight_layout()
plt.show()

sns.catplot with kind='count' ordered by count

Upvotes: 1

Related Questions