ggplot2 - 如何使用值按标签重新排序堆积条形图数据点,而不是按字母顺序排序

时间:2018-06-17 17:15:41

标签: r ggplot2 forcats

我想重新排序堆积的条形图数据点,以便在每个条形图中按照其总VALUE从最大到最小的COMPETITOR排序,而不是按字母顺序排序。

我生成数据以使用fct_reorder(注释掉的行)并且数据点被排序但标签不遵循更改的顺序。 如何使图上的标签跟随并位于条形段中间的正确位置?

这是我的工作可重复示例,其中fct_reorder行被注释掉了。如果取消注释,数据点将被排序,但标签将保持在错误的位置。

library(tidyverse)
library(scales)


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


unit_mln <-
  scales::unit_format(
    unit = "mln",
    sep = " ",
    scale = 1e-6,
    digits = 2,
    justify = "right"
  )

col_competitors <-
  scale_fill_manual( "legend", 
                     values = c(
                       "XXX" = "navyblue",   "YYY" = "red",
                       "ZZZ" = "lightyellow", "VVV" = "green"))



df_cust<- data %>% mutate(COMPETITOR=as.factor(COMPETITOR)) %>% 
  group_by(CUSTOMER) %>%                                                    
  mutate(CUST_VALUE=sum(VALUE)) %>%                                 
  ungroup() %>% 
  group_by(COMPETITOR) %>%      
  mutate(COMP_VALUE=sum(VALUE)) %>%                                 
  ungroup() %>% 
  group_by(CUSTOMER,  COMPETITOR) %>%                                           
  summarise(CUST_VALUE=max(CUST_VALUE), COMP_VALUE=max(COMP_VALUE), VALUE=sum(VALUE))%>% 
  arrange(desc(CUST_VALUE))

# df_cust<-df_cust %>% mutate(COMPETITOR= fct_reorder(COMPETITOR, -COMP_VALUE))



df_comp<- data %>% group_by(COMPETITOR) %>% summarise(VALUE=sum(VALUE)) 

df_cust$CUSTOMER = str_wrap(df_cust$CUSTOMER, width = 30)



plt_main<-df_cust %>% 
  ggplot(aes(x = fct_reorder(CUSTOMER, -CUST_VALUE), y = VALUE)) +
  geom_col(
    aes(fill = COMPETITOR),
    alpha = 0.5,
    position = position_stack(reverse = T),
    col = "darkgray",
    show.legend = F ) +
  geom_text(aes(label = unit_mln(round(VALUE,-4))),
            size = 3,
            position = position_stack(vjust = 0.5)) +
  xlab(" ") + ylab("Market share (GROSS PLN)") + ggtitle(paste("Top competitors in top customers: ", "Poland")) +
  theme_bw(base_size = 11) +
  theme(
    axis.text.x = element_text(
      angle = 90,
      hjust = 1,
      vjust = 0.5 ),
    legend.position = c(0.94, 0.75)) +
  col_competitors +
  scale_y_continuous(
    labels = function(n) {
      unit_mln(n)
    },
    sec.axis = sec_axis(~ . / sum(df$VALUE), labels = scales::percent)
  )

2 个答案:

答案 0 :(得分:1)

我认为以下内容应该这样做:

ggplot(df, aes(x = reorder(CUSTOMER, -COMP_VALUE), y = VALUE))

按COMP_VALUE命令CUSTOMER列。

答案 1 :(得分:0)

我评论了#****#****描述****`可以在堆积的条形图中对数据点和标签进行排序的行。 现在他们按照COMPETITOR的总销售额订购,而不是按字母顺序排列。 我承认我通过反复试验来实现它,这可能不是最佳答案。

library(tidyverse)
library(scales)

# 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)

# Format labels with scales package

unit_mln <-
  unit_format(
    unit = "mln",
    sep = " ",
    scale = 1e-6,
    digits = 2,
    justify = "right"
  )

# Set your own colors for competitors

col_competitors <-
  scale_fill_manual( "legend", 
                     values = c(
                       "XXX" = "navyblue",   "YYY" = "red",
                       "ZZZ" = "lightyellow", "VVV" = "green"))


# Generate helper data for ordering: totals for CUSTOMER and COMPETITOR.

df_cust<- data %>% mutate(COMPETITOR=as.factor(COMPETITOR)) %>% 
  group_by(CUSTOMER) %>%                                                    
  mutate(CUST_VALUE=sum(VALUE)) %>%                                 
  ungroup() %>% 
  group_by(COMPETITOR) %>%      
  mutate(COMP_VALUE=sum(VALUE)) %>%                                 
  ungroup() %>% 
  group_by(CUSTOMER,  COMPETITOR) %>%                                           
  summarise(CUST_VALUE=max(CUST_VALUE), COMP_VALUE=max(COMP_VALUE), VALUE=sum(VALUE))%>% 
  arrange(desc(CUST_VALUE))

# Reorder COMPETITOR by total VALUE descening                       #***this is needed to reorder labels***
df_cust<-df_cust %>% mutate(COMPETITOR= reorder(COMPETITOR, -COMP_VALUE))


# Prepare data for a small "legend" plot
df_comp<- data %>% group_by(COMPETITOR) %>% summarise(VALUE=sum(VALUE)) 

# Wrap CUSTOMER names if too long
df_cust$CUSTOMER = str_wrap(df_cust$CUSTOMER, width = 30)

# Main plot
(
plt_main<-df_cust %>% 
  ggplot(aes(x = fct_reorder(CUSTOMER, -CUST_VALUE), y = VALUE)) +  #***this fct_ reorders bars***
  geom_col(
    aes(fill = COMPETITOR),
    alpha = 0.5,
    position = position_stack(reverse = T),
    col = "darkgray",
    show.legend = F ) +
  geom_text(aes(label = unit_mln(round(VALUE,-4)), 
                group=fct_reorder(COMPETITOR, COMP_VALUE)),         #***this fct_ reorders labels***
            size = 3, 
            position = position_stack(vjust = 0.5, reverse=F)) +
  xlab(" ") + ylab("Market share (GROSS PLN)") + ggtitle(paste("Top competitors in top customers: ", "Poland")) +
  theme_bw(base_size = 11) +
  theme(
    axis.text.x = element_text(
      angle = 90,
      hjust = 1,
      vjust = 0.5 ),
    legend.position = c(0.94, 0.75)) +
  col_competitors +
  scale_y_continuous(
    labels = function(n) {
      unit_mln(n)
    },
    sec.axis = sec_axis(~ . / sum(df_cust$VALUE), labels = scales::percent)
  )
)