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)
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?
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()
Or you can stack the bars:
titanic.groupby(['pclass', 'sex'])['survived'].mean().unstack('sex').plot(kind='bar', stacked=True)
Why you use mean
instead of count
?
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 *
Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived)', column='sex').configure_cell(width=200, height=200)
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)
Chart(titanic).mark_bar().encode(x='pclass:O', y='mean(survived):Q', color='sex:O').configure_cell(width=200, height=200)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.