ggplot将cut cut abline添加到堆积的条形图中,条件:阈值达到

时间:2018-06-19 08:04:24

标签: r ggplot2 dplyr tidyverse

我想画出一条垂直线,将竞争对手与其他竞争对手分开,占70%的市场份额。 这是示例数据。

# Example data

data<- tibble::tribble(
  ~CUSTOMER, ~COMPETITOR, ~VALUE,
      "AAA",    "XXX",  123400,
      "AAA",    "YYY",   10000,
      "AAA",    "ZZZ",   80000,
      "AAA",    "YYY",   60000,
      "BBB",    "XXX",  110000,
      "BBB",    "YYY",   20000,
      "BBB",    "ZZZ",   10000,
      "BBB",    "YYY",   80000,
      "CCC",    "YYY",   30000,
      "CCC",    "ZZZ",   12000,
      "DDD",    "YYY",    7000,
      "CCC",    "VVV",   10000)

这是我对情节的汇总:

library (tidyverse) 
   df_COMP<- data %>%                          # totals and pareto for COMPETITOR
      group_by(COMPETITOR) %>%      
      summarise(COMP_VALUE=sum(VALUE)) %>%                                 
      arrange(desc(COMP_VALUE)) %>% 
      mutate(COMP_PARETO=cumsum(COMP_VALUE)/total_VALUE) %>%  
      ungroup()

我绘制了一个有序下降的堆积条形图。

df_COMP %>% 
  ggplot(aes(x = fct_reorder(COMPETITOR, -COMP_VALUE), 
                               y = COMP_VALUE)) + 
  geom_col(alpha=0.4, aes(fill=COMPETITOR), col = "darkgray", show.legend = F)+
  ggtitle(" ")+
  theme_bw(base_size = 11)+ col_competitors  +
  theme(axis.text.x = element_text(angle = 90, hjust=1, vjust=0.5, size=10),
        axis.title=element_blank(),
        axis.ticks=element_blank())+
  scale_y_continuous(labels = function(n){unit_mln(n)}, 
                     sec.axis = sec_axis(~. / sum(df_COMP$COMP_VALUE), labels = scales::percent))+
  scale_x_discrete()+
  geom_text(aes(label = unit_mln(COMP_VALUE)), size = 3, position = position_stack(vjust = 0.5))

如何添加到这个堆叠的条形图,一个将竞争对手分成阈值的hline,比如基于COMP_PARETO列的70%,其中包含累计销售百分比。如果x轴是数字但是它们是绝对的,那将很容易。

0 个答案:

没有答案