DatCra
DatCra

Reputation: 373

Pandas groupby plot with different X-Axis order

I'm working on titanic.csv, and trying to make some plots. Running into one issue. How can I re-organize the x-axis to place the same pclass value next to each other.

my current code:

titanic.groupby(['Sex', 'Pclass'])['Survived'].mean().plot(kind='bar', color=my_colors)

produce the following chart: enter image description here

I'd like to place the male and female from same class next to each other to show the difference in survival rate. Any suggestion?

Upvotes: 3

Views: 2533

Answers (2)

Nipun Batra
Nipun Batra

Reputation: 11377

Altair can be very handy here. Here are 3 different one-liners to produce three different visualisations of this dataset.

import seaborn as sns
titanic = sns.load_dataset("titanic")

from altair import *

First viz.

Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived)', column='sex').configure_cell(width=200, height=200)

enter image description here

Second viz.

Chart(titanic).mark_bar().encode(x='sex:N', y='mean(survived):Q',  column='pclass:O').configure_facet_cell(
        strokeWidth=0.0).configure_cell(width=200, height=200)

enter image description here

Third viz.

Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived):Q',  color='sex:O').configure_cell(width=200, height=200)

enter image description here

Upvotes: 0

Serenity
Serenity

Reputation: 36695

Just change the order of columns in groupby:

import pandas as pd
import seaborn as sns
import matplotlib.pylab as plt

titanic = sns.load_dataset("titanic")

my_colors = ['r','g','b','k','y','magenta']
titanic.groupby(['pclass', 'sex'])['survived'].mean().plot(kind='bar', color=my_colors)
plt.show()

enter image description here

Or you can stack the bars:

titanic.groupby(['pclass', 'sex'])['survived'].mean().unstack('sex').plot(kind='bar', stacked=True)

enter image description here

Why you use mean instead of count?

Upvotes: 2

Related Questions