R中的反向堆叠条形图导致奇怪的位置

问题描述 投票:1回答:1

我正在尝试在R中创建堆积的条形图,并颠倒顺序。

df <- structure(list(HouseholdEarnings = structure(c(2L, 2L, 3L, 3L, 
3L, 2L, 2L, 1L, 4L, 2L, 3L, 6L, 5L, 4L, 2L, 1L, 2L, 3L, 1L, 3L, 
3L, 3L, 2L, 2L, 2L, 6L, 2L, 5L, 2L, 6L, 2L, 2L, 3L, 1L, 3L, 2L, 
4L, 2L, 1L, 3L, 2L, 1L, 5L, 3L, 3L, 3L, 2L, 2L, 3L, 2L, 1L, 3L, 
3L, 4L, 2L, 2L, 3L, 2L, 3L, 3L, 2L, 2L, 6L, 4L, 3L, 3L, 2L, 3L, 
4L, 2L, 2L, 3L, 2L, 4L, 1L, 1L, 2L, 2L, 2L, 4L, 4L, 6L, 3L, 4L, 
2L, 4L, 4L, 2L, 4L, 6L, 3L, 4L, 1L, 2L, 4L, 2L, 2L, 5L, 3L, 2L
), .Label = c("Below $2,000 per month", "$2,000 - $3,999", "$4,000 - $5,999", 
"$6,000 - $7,999", "$8,000 - $9,999", "$10,000 & above"), class = c("ordered", 
"factor"))), row.names = c(NA, -100L), class = "data.frame")

基于来自其他线程的解决方案,将geom_col(position = position_stack(reverse = TRUE))放置可以解决该问题。

df %>% group_by(HouseholdEarnings) %>% summarise(Count = n()) %>% mutate(Proportion=Count/sum(Count), group='All') %>%
  as.data.frame() %>% mutate_if(is.numeric, round, digits = 2) %>%
  ggplot(aes(fill=HouseholdEarnings, y=Proportion, x=group)) +
  geom_col(position = position_stack(reverse = T), color = "black") +
  geom_text(aes(label=paste0(Proportion*100, "%")),
                position=position_stack(vjust=0.5), colour="white",size=3) +
  coord_flip()

但是,现在我的标签不正确(仍然在原始位置):

enter image description here

不用reverse = T就可以了:

df %>% group_by(HouseholdEarnings) %>% summarise(Count = n()) %>% mutate(Proportion=Count/sum(Count), group='All') %>%
  as.data.frame() %>% mutate_if(is.numeric, round, digits = 2) %>%
  ggplot(aes(fill=HouseholdEarnings, y=Proportion, x=group)) +
  geom_col(position = position_stack(), color = "black") +
  geom_text(aes(label=paste0(Proportion*100, "%")),
                position=position_stack(vjust=0.5), colour="white",size=3) +
  coord_flip()

enter image description here

编辑:我意识到只有标签仍然固定在其原始位置,所以有什么方法可以翻转它们?

r ggplot2 bar-chart stacked-chart
1个回答
1
投票

您也需要在reverse = TRUE中传递geom_text

df %>% group_by(HouseholdEarnings) %>% summarise(Count = n()) %>% mutate(Proportion=Count/sum(Count), group='All') %>%
  as.data.frame() %>% mutate_if(is.numeric, round, digits = 2) %>%
  ggplot(aes(fill=HouseholdEarnings, y=Proportion, x=group)) +
  geom_col(position = position_stack(reverse = T), color = "black") +
  geom_text(aes(label=paste0(Proportion*100, "%")),
            position=position_stack(reverse = TRUE, vjust = 0.5), colour="white",size=3) +
  coord_flip()

enter image description here

它回答了您的问题吗?

© www.soinside.com 2019 - 2024. All rights reserved.