[R] Using ggplot2 to plot percentages in bar chart.
Shawn Way
SWay at meco.com
Mon Dec 5 20:16:07 CET 2016
I have the following data in which I'm trying to summarize in a stacked bar plot showing the percentages as a label in the bar.
The data is as follows:
> head(data)
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>
It is then transformed using dplyer:
> d2 <- data %>%
gather(Model,Status) %>%
group_by(Model,Status) %>%
summarise(count=n()) %>%
mutate(perc=count/sum(count))
giving
> head (d2)
Source: local data frame [6 x 4]
Groups: Model [2]
Model Status count perc
<chr> <chr> <int> <dbl>
1 MASTERPAK10LT C 8 0.21052632
2 MASTERPAK10LT X 29 0.76315789
3 MASTERPAK10LT <NA> 1 0.02631579
4 MASTERPAK22LT C 6 0.15789474
5 MASTERPAK22LT U 1 0.02631579
6 MASTERPAK22LT X 30 0.78947368
I then try to plot this using ggplot using
plt <- ggplot(d2,aes(x=Model,y= perc,fill=Status)) +
geom_bar(stat="identity") +
labs(y="Percent Complete") +
stat_bin(geom = "text",
aes(label=paste(round(perc*100),"%")),
vjust=5) +
scale_y_continuous(labels = percent)
but I get the error:
Error: stat_bin() must not be used with a y aesthetic.
When I leave out the stat_bin, I get the correct bar chart, but without the labels. Can someone please help me understand what is causing the error above?
Thank you kindly,
Shawn Way, PE
More information about the R-help
mailing list