I would like to create a bar chart with ggplot in R.
The sample data is as follows:
Name <- c('Sample1', 'Sample2', 'Sample3')
Total <- c(86020045,30974095,1520609)
Part <- c(41348957, 2956650, 595121)
DT <- data.frame(Name,Total,Part)
ggplot(DT, aes(Name, Total, fill=Name)) +
Oh... It seems like someone already commented the answer while I was writing it down. I'll post mine anyways since it's slightly different.
DT <- transform(DT, Part0 = Total - Part) library(reshape2) DT2 <- melt(DT, id.vars = c("Name", "Total")) DT2 <- transform(DT2, perc = value/Total * 100) ggplot(DT2, aes(Name, perc, fill=variable)) + geom_bar(position="stack",stat="identity") + geom_text(data = subset(DT2, variable == "Part"), aes(y = (perc), label = paste0("Total = ", Total, "\n", "Part = ", value, "\n", round(perc, 1), "%\n")))
If you use
value instead of
perc you will get a proportional bar chart but since the total for sample 3 is a lot smaller than sample 1, it's going to be difficult to read the table. So I decided to use percentage instead of the actual values.