我想重新排序堆叠的条形图数据点,以便在每个条形图中,它们按其总价值从最大到最小的竞争对手排序,而不是按字母顺序排序。
我生成数据以使用 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)
)