Home > Mobile >  How to clean up numbered labels on the bar graph
How to clean up numbered labels on the bar graph

Time:09-30

I was wondering how I could go about cleaning up the numbers on the graph. Attached is a sample dataframe with the code. The actual database is 1300 entries. Ill be cleaning up the NAs and misc entries. But I would like to keep the total numbers and the percentages for the categories in a way that's legible.

Thank you!

UnnestQ3 <- data.frame(Q3 = c ("mail", "email", "mail", "mail", 
                            "Demonstration", "Videos (Ex: Youtube)",
                            "Podcast", "Podcast", "mail"), Gender = c ("male", "male", "female", "male", "female", "NA", "NA", "Other", "Male")

ggplot(UnnestQ3, aes(x = Q3, fill = D1))  
      geom_bar(width = 0.75)  
      theme_minimal(base_size = 10)  
       geom_text(aes(label = paste0(..count..,"(",round(..count..*100/nrow(UnnestQ3)), "%)")), stat = "count", vjust = 0, colour = "black")  
      coord_flip()  
      labs(x = "Communication Method")  
      labs(y = "Total Number of Responses (N)")  
      scale_fill_viridis_d()

Bar graph

CodePudding user response:

You need to use position_stack in your text layer. I would also make the text color conditional on Gender so that it is legible against dark background fills:

ggplot(UnnestQ3, aes(x = Q3, fill = Gender))  
 geom_bar(width = 0.75)  
 theme_minimal(base_size = 10)  
 geom_text(aes(label = paste0(..count..," (", 
                              round(..count..*100/nrow(UnnestQ3)), "%)"),
               color = Gender), 
           stat = "count", vjust = 0,  
           position = position_stack(vjust = 0.5))  
   scale_color_manual(values = c("white", "white", "white", "black", "black"),
                      guide = "none")  
   coord_flip()  
   labs(x = "Communication Method")  
   labs(y = "Total Number of Responses (N)")  
   scale_fill_viridis_d()

enter image description here

  • Related