ggplot2/plotnine:如何为熔融df绘制分组图表?

2024-06-17 11:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我将一个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

“主机id”实际上表示此处的计数:

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

enter image description here


Tags: 数据idhost绘图valuecount错误绘制
1条回答
网友
1楼 · 发布于 2024-06-17 11:03:57
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)
    })

我没有您的dataframe,因此请检查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

相关问题 更多 >