Pandas group plot with different X-Axis order
I am working on titanic.csv
and am trying to do some plots. Start in one question. How can I re-arrange the X-axis to position the same pclass value next to each other.
my current code:
titanic.groupby(['Sex', 'Pclass'])['Survived'].mean().plot(kind='bar', color=my_colors)
I would like to put men and women from the same class next to each other to show the difference in survival. Any suggestion?
+3
source to share
2 answers
Just change the order of the 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()
Or you can add lines:
titanic.groupby(['pclass', 'sex'])['survived'].mean().unstack('sex').plot(kind='bar', stacked=True)
Why are you using mean
instead count
?
+2
source to share
Altair can be very handy here. Here are three different one-line interfaces for creating three different visualizations of this dataset.
import seaborn as sns
titanic = sns.load_dataset("titanic")
from altair import *
First view
Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived)', column='sex').configure_cell(width=200, height=200)
Second aspect.
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)
Third:
Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived):Q', color='sex:O').configure_cell(width=200, height=200)
0
source to share