Skip to content
Prev 365856 / 398502 Next

Using ggplot2 to plot percentages in bar chart.

I don't understand how your labelling technique was supposed to work. 
Below is my reproducible example of how I would approach this problem.
When you post next time, try to follow this method of making something we 
can put into our fresh R environment and see your problem directly.

---
library(dplyr)
library(tidyr)
library(ggplot2)

dta <- read.table( text=
"  MASTERPAK2LT MASTERPAK4LT MASTERPAK7LT MASTERPAK10LT MASTERPAK22LT
1            X            X            X             X             X
2            C            C            C             X             X
3            C            C            C             X             X
4            U            U            X             X             X
5           NA            U            X             X             X
6           NA           NA            X            NA            NA
", header=TRUE, as.is=TRUE )

d2 <- dta %>%
     gather( Model, Status ) %>%
     group_by( Model, Status ) %>%
     summarise( count = n() ) %>%
     group_by( Model ) %>%
     mutate( perc = 100 * count / sum( count )
           , percpos = rev( cumsum( rev( perc ) ) - 0.5 * rev( perc ) )
           ) %>%
     ungroup %>%
     mutate( Modelf = factor( Model )
           , percLbl = sprintf( "%2.0f%%", perc )
           )

plt <- ggplot( d2
              , aes( x = Modelf
                   , y = perc
                   , fill = Status
                   )
              ) +
     geom_bar( stat = "identity" ) +
     labs( x = "Model", y = "Percent Complete" ) +
     geom_text( mapping = aes( x = Modelf
                             , y = percpos
                             , label = percLbl )
              , vjust = 0.5 )
plt
---
On Mon, 5 Dec 2016, Shawn Way wrote:

            
---------------------------------------------------------------------------
Jeff Newmiller                        The     .....       .....  Go Live...
DCN:<jdnewmil at dcn.davis.ca.us>        Basics: ##.#.       ##.#.  Live Go...
                                       Live:   OO#.. Dead: OO#..  Playing
Research Engineer (Solar/Batteries            O.O#.       #.O#.  with
/Software/Embedded Controllers)               .OO#.       .OO#.  rocks...1k