标签在堆叠的条形图中被错误地反转

时间:2018-11-29 17:15:19

标签: r ggplot2

堆积的条形图上的标签没有出现在正确的条形图上;相反,它们的位置对应于反转的柱线顺序。

enter image description here

示例数据集:

library(scales)
library(ggplot2)
types <- c('Mostly Satisfied','Somewhat satisfied','Unsatisfied')
df_summ <- data.frame(cust_type = factor(types, levels=types),
                      cust_count = c(1.2e3, 2.3e3, 3.4e3)
                      )
df_summ$percent_of_file <- df_summ$cust_count/sum(df_summ$cust_count)
df_summ$label_txt <- paste0(df_summ$cust_type,': ',comma(df_summ$cust_count),' (',
                            percent(df_summ$percent_of_file),')')

# I need a dummy value for the x axis
df_summ$group <- 'All customers'

我的情节代码:

ggplot(df_summ,
       aes(x=group, y = cust_count, label=label_txt))+
  geom_bar(aes(fill=cust_type),position='stack',stat='identity')+
  geom_text(size = 4, 
            position = position_stack(vjust = 0.5,
                                  reverse=TRUE) # changing to reverse=FALSE doesn't help
            )+
  scale_fill_manual(values = setNames(c('green','beige','salmon'), types),
                    guide=FALSE
  ) +
  labs( x = NULL,
        y = NULL,
        title = 'Composition of customer base') +
  theme_minimal() +
  theme ( panel.grid.major = element_blank(), 
            panel.grid.minor = element_blank(),
            axis.text.x=element_blank(),
            axis.ticks.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks.y=element_blank()
          )

如何在保持条形顺序的同时固定标签的位置?

我的问题有点像this question,但带有条形图,解决方案(使用position_stack())对我没有帮助。

1 个答案:

答案 0 :(得分:1)

我会在fill = cust_type的美感中添加label = label_txt并将其从ggplot()的美学中删除。我将aes(label = label_txt)添加到geom_text()并将reverse = TRUE更改为reverse = FALSE。然后,绘图的R代码应如下所示,并有望正常工作:

ggplot(
  data = df_summ
  ,aes(
    x = group
    ,y = cust_count
    ,fill = cust_type)) +
geom_bar(
  position = 'stack'
  ,stat = 'identity') +
geom_text(
  aes(label = label_txt)
  ,size = 4
  ,position = position_stack(
    vjust = 0.5
    ,reverse = FALSE)) +
scale_fill_manual(
  values = setNames(
    c('green','beige','salmon')
    ,types)
  ,guide = FALSE) +
labs(
  x = NULL
  ,y = NULL
  ,title = 'Composition of customer base') +
theme_minimal() +
theme(
  panel.grid.major = element_blank()
  ,panel.grid.minor = element_blank()
  ,axis.text.x = element_blank()
  ,axis.ticks.x = element_blank()
  ,axis.text.y = element_blank()
  ,axis.ticks.y = element_blank());