Search code examples
rggplot2geom-bar

How to position a label text at the outside end of horizontal bar graph (ggplot) when label is unrelated to fill?


I have a dataset that looks like the following below. I am making a horizontal bar chart with ggplot that plots number of students (filled by status) but I want the label (the total students who completed the work to be at the end of the bar so you can see the total n but also % completed. I have the code I am currently using. I'm trying to figure out how to do hjust based on the rate rather then the number of students. Do I need to adjust the dataframe with new info or different info to make this easier or can I use something with hjust to put the label at the outside end of the bar chart?

   State      Number of Students Rate Denominator Status        Label
1     CT                   4500 0.471        8500 Completed     47.1%
2     CT                   4000 0.471        8500 Not Completed <NA>
3     OK                   4375 0.653        6700 Completed     65.3%
4     OK                   2325 0.653        6700 Not Completed <NA>
5     TX                   5040 0.70         7200 Completed     70.0%
6     TX                   2160 0.70         7200 Not Completed <NA>

ec <- ggplot(data, aes(y=reorder(State, Rate), x= `Number of Students`, fill = Status)) +
  geom_bar(stat = "identity") + 
  scale_fill_brewer(palette = "Dark2") +
  ggtitle("Completed Rates by State")+
  ylab("State") +
  geom_text(aes(label=label))

Solution

  • df <- data.frame(state = c('CT', 'CT', 
                               'OK', 'OK', 
                               'TX', 'TX'), 
               numberOfStudents = c(4500, 4000, 
                                    4375, 2325, 
                                    5040, 2160), 
               denominator =  c(8500, 8500,
                                6700, 7600, 
                                7200, 7200), 
               rate = c( 0.471, 
                         0.471, 
                         0.653, 
                         0.653, 
                         0.70, 0.70),
               status = c('Completed', 'Not Completed', 
                          'Completed','Not Completed', 
                          'Completed', 'Not Completed'), 
               label = c('47.1%',  NA, '65.3%', NA, '70.0%', NA)
    )
    
    ggplot() +
      geom_bar(data = df, 
               mapping = aes(y=reorder(state, rate), 
                             x= numberOfStudents, 
                             fill = status), 
               stat = "identity") + 
      scale_fill_brewer(palette = "Dark2") +
      ggtitle("Completed Rates by State")+
      ylab("State") +
      xlim(0, 9000)+
      geom_text(data = df, 
                mapping = aes(y = state, 
                              x = denominator, 
                              label=label), 
                hjust = 0)
    

    sample