从 Summarize 和 Facet Wrap 获取比例图

Get Proportion Graph From Summarise and Facet Wrap

我有三个分类变量和一个数值变量;我想通过根据我的分类变量分割数据并获取数字变量的比例来显示比例。

数据如下:

ID Brand   Color    Gear Sales
1  Honda   Blue     M    80
2  Toyota  Blue     A    75
3  Ford    Blue     M    25
4  Honda   Red      M    100
5  Toyota  Red      M    125
6  Ford    Red      M    90
7  Honda   Green    A    15
8  Toyota  Green    M    120
9  Ford    Green    A    65

本质上,我想要一个条形图来显示品牌的 facet_wrap 每种颜色的销售额比例。

结果将是本田 80 Blue/195 总计、100 红色/185 总计和 15 绿色/185 总计等...条形图中显示的百分比:

a <-  df%>% group_by(Brand, Color)

b <-  summarise(a, sales_amt = sum(Sales),
                   brand_sale = sum("Here is where I am having the issue"),
                   sales_percentage = (sales_amt/brand_sale))

c <-  ggplot(b) + 
        geom_bar(aes(Color, sales_percentage) , stat = "identity") + 
        facet_wrap(~ Brand)
c

考虑以 R 为基数的 ave 以按组对销售百分比的分母进行内联聚合:

df <- within(df, {       
   brand_sale <- ave(Sales, Brand, FUN=sum)
   sales_percentage <- Sales / brand_sale       
})

df    
#   ID  Brand Color Gear Sales sales_percentage brand_sale
# 1  1  Honda  Blue    M    80       0.41025641        195
# 2  2 Toyota  Blue    A    75       0.23437500        320
# 3  3   Ford  Blue    M    25       0.13888889        180
# 4  4  Honda   Red    M   100       0.51282051        195
# 5  5 Toyota   Red    M   125       0.39062500        320
# 6  6   Ford   Red    M    90       0.50000000        180
# 7  7  Honda Green    A    15       0.07692308        195
# 8  8 Toyota Green    M   120       0.37500000        320
# 9  9   Ford Green    A    65       0.36111111        180

c <-  ggplot(df) + 
  geom_bar(aes(Color, sales_percentage) , stat = "identity") + 
  facet_wrap(~ Brand)
c