【问题标题】:labels are incorrectly reversed in stacked bar chart标签在堆积条形图中错误地反转
【发布时间】:2018-11-29 17:15:19
【问题描述】:

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

示例数据集:

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())在这里对我没有帮助。

【问题讨论】:

  • 您在调用scale_fill_manual 时使用character 类型,但在实际数据中使用factor(types)。也许您应该最初将它们转换为 factor 而不仅仅是数据?
  • 问题是你没有给文本层任何变量来“堆叠”,因为你把fill美学放在geom_bar()中。您可以将其移至全局 aes()(即在 ggplot() 中)或将 aes(group = cust_type) 之类的内容添加到 geom_text() 中。您不需要反转堆叠。
  • @r2evans 感谢您的建议。我最初尝试转换它们,但没有任何区别。
  • @aosmith 这很有意义。谢谢。

标签: r ggplot2


【解决方案1】:

我会将fill = cust_type 添加到label = label_txt 并将label = label_txtggplot() 的美学中删除。我会将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()); 

【讨论】:

  • TYVM。我没有移动aes(label),它仍然有效。
猜你喜欢
  • 2013-12-22
  • 2021-10-25
  • 1970-01-01
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多