簡體   English   中英

ggplot2-如何使用值而不是按字母順序對帶有標簽的堆疊條形圖數據點進行重新排序

[英]ggplot2 - how to reorder stacked bar plot datapoints with labels by values and not alphabetically

我想對堆疊的條形圖數據點進行重新排序,以便在每個條形圖中按其總值從最大到最小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)
  )

我認為以下應該這樣做:

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

這將按COMP_VALUE對CUSTOMER列進行排序。

我對“#**** description ****”進行了注釋,這些行使得可能在堆疊的條形圖中對數據點和標簽進行排序。 現在,它們是根據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)
  )
)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM