ggplot2 / plotnine:如何绘制融化的df的分组图表?

我子集并融化了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)

融化的数据集如下:

ggplot2 / plotnine:如何绘制融化的df的分组图表?

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

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'

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

ggplot2 / plotnine:如何绘制融化的df的分组图表?

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

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

ggplot2 / plotnine:如何绘制融化的df的分组图表?

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

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

ggplot2 / plotnine:如何绘制融化的df的分组图表?

gddgv 回答:ggplot2 / plotnine:如何绘制融化的df的分组图表?

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

本文链接:https://www.f2er.com/2750714.html

大家都在问