Skip to content
Prev 365870 / 398502 Next

Using ggplot2 to plot percentages in bar chart.

This worked well!  Thank you very much.

For the record, the stat_bin was used in a solution I found on stackexchange for something similar, but I was having issues adapting.

Thanks again to all who responded.  I appreciate it greatly.

Shawn Way, PE

-----Original Message-----
From: Jeff Newmiller [mailto:jdnewmil at dcn.davis.ca.us] 
Sent: Tuesday, December 06, 2016 12:13 AM
To: Shawn Way <SWay at meco.com>
Cc: John Kane <jrkrideau at yahoo.ca>; r-help at r-project.org
Subject: Re: [R] 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