I am trying to create a stacked bar plot in R, and to reverse the order.
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")
Based on solutions from other threads, putting geom_col(position = position_stack(reverse = TRUE))
solved the issue.
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()
However, now my labels are out of position (still in the original positions):
It is fine without using 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()
Edit: I realize that only the labels are still fixed to their original positions, so is there any way to flip them?