gpt4 book ai didi

python - ggplot2/图九 : How to plot grouped chart for a melted df?

转载 作者:行者123 更新时间:2023-12-01 06:33:18 25 4
gpt4 key购买 nike

我对 Airbnb 数据集进行子集化和融合,并尝试绘制分组图表:

from plotnine import *

airbnb_melted = pd.melt(airbnb_newcomers, id_vars =['host_id'], value_vars =['host_identity_verified', 'host_is_superhost'])
print(airbnb_melted)

融化的数据集如下所示:

enter image description here

我知道我的以下代码是错误的,并且绘图的输出不是我想要的,但它最接近我的想法:

ggplot(airbnb_melted, aes(x='variable', y='value')) +\
geom_bar(stat = 'sum', position=position_dodge())

我在网上搜索了一下,发现了很多带有 y 的情节示例。作为数值变量和 stat='count'可以使用。然而,y这是分类的,它显示错误 PlotnineError: 'stat_count() must not be used with a y aesthetic'

如何绘制类似于以下格式的分组条形图?橙色的字是我添加的作为指示。谢谢。

enter image description here

2020年1月20日更新:感谢@StupidWolf的帮助,编码工作如下:

airbnb_host_count = airbnb_melted.replace(np.NaN, 'NA').groupby(['value', 'variable']).count().reset_index()

enter image description here

“host_id”实际上表示此处的计数:

ggplot(airbnb_host_count, aes(x='variable', y='host_id', fill='value')) +\ 
geom_bar(stat='sum', position=position.dodge())

enter image description here

最佳答案

Try this:

from plotnine import *
import pandas as pd
import numpy as np
import random

random.seed(99)
airbnb_melted = pd.DataFrame(
{'host_id':np.arange(20),
'variable': np.repeat(['host_identity_verified','host_is_superhost'],[10,10]) ,
'value' : random.choices(['t','f','NA'],k=20)
})

我没有你的数据框,所以检查 NA 值到底是什么,然后像这样替换它,例如如果它是 NaN

airbnb_melted = airbnb_melted.replace(np.NaN,'NA')

我们可以检查计数:

airbnb_melted.groupby(['value','variable']).count()

value variable
NA host_identity_verified 3
host_is_superhost 2
f host_identity_verified 3
host_is_superhost 6
t host_identity_verified 4
host_is_superhost 2

现在我们绘图,您设置 fill = 'value' 并且不设置 'stat',因为默认值为 'count',它会计算您的 t、f 和 NA:

ggplot(airbnb_melted, aes(x='variable', fill='value')) +\
geom_bar(position=position_dodge())

enter image description here

关于python - ggplot2/图九 : How to plot grouped chart for a melted df?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59792741/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com