Home > Software engineering >  Flip the fill variable with geom_bar(position="fill, stat = "identity) in ggplot
Flip the fill variable with geom_bar(position="fill, stat = "identity) in ggplot

Time:04-02

I have the following code :

newdf %>%
  ggplot()  
  aes(x = smoke_status, y = Count, fill = Birth_status)   
  xlab("Smoking Activity")  
  ylab("Proportion")  
  labs(fill = "Birthweight")  
  geom_bar(position = "fill", stat = "identity")  
  scale_y_continuous(labels = scales::percent) 
  

enter image description here

How can I change the plot so that the percentage in red corresponding to "low birth weight" is at the bottom of the bar chart?

Thank you in advance!

If you want to test with my dataframe I used the opt dataset from the medicaldata package:

install.packages("medicaldata")
library(medicaldata)

newdf = opt %>% 
  filter(BL.Cig.Day != "NA", Birthweight != "NA") %>%
  select(c(cig = BL.Cig.Day, Birthweight)) %>%
  mutate(cig = as.double(cig), Birthweight = as.double(Birthweight)) %>%
  mutate(smoke_status = case_when(cig >= 9 ~ "High", cig <9 ~ "Normal"),
         Birth_status = case_when(Birthweight < 2500 ~ "Low", Birthweight >=2500~ "Normal")
         ) %>%
  group_by(smoke_status, Birth_status) %>%
  summarize(Count = n())
  

CodePudding user response:

You could reverse the stack order via position = position_fill(reverse = TRUE):

library(ggplot2)

ggplot(newdf)  
  aes(x = smoke_status, y = Count, fill = Birth_status)   
  xlab("Smoking Activity")  
  ylab("Proportion")  
  labs(fill = "Birthweight")  
  geom_bar(position = position_fill(reverse = TRUE), stat = "identity")  
  scale_y_continuous(labels = scales::percent)

DATA

newdf <- structure(list(smoke_status = c("High", "High", "Normal", "Normal"), Birth_status = c("Low", "Normal", "Low", "Normal"), Count = c(
  10L,
  34L, 4L, 44L
)), class = c("grouped_df", "tbl_df", "tbl", "data.frame"), row.names = c(NA, -4L), groups = structure(list(smoke_status = c(
  "High",
  "Normal"
), .rows = structure(list(1:2, 3:4), ptype = integer(0), class = c(
  "vctrs_list_of",
  "vctrs_vctr", "list"
))), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L), .drop = TRUE))
  • Related