简体   繁体   中英

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: 在此输入图像描述

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 *

First viz.

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

在此输入图像描述

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)

在此输入图像描述

Third viz.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM