简体   繁体   English

Pandas groupby以不同的X轴顺序绘制

[英]Pandas groupby plot with different X-Axis order

I'm working on titanic.csv , and trying to make some plots. 我正在研究titanic.csv ,并尝试制作一些情节。 Running into one issue. 遇到一个问题。 How can I re-organize the x-axis to place the same pclass value next to each other. 如何重新组织x轴以将相同的pclass值放在一起。

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: 只需更改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 ? 为什么你使用mean而不是count

Altair can be very handy here. Altair在这里非常方便。 Here are 3 different one-liners to produce three different visualisations of this dataset. 这里有3个不同的单行生成这个数据集的三个不同的可视化。

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)

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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