silverrain silverrain - 1 year ago 79
R Question

How to overwrap on geom_bar in ggplot2?

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)) +

What I would like to show is the stack bar chart that shows each Name's Total counts, and show the Part counts within the bar + label the % of it on in the middle of the bar.

Is there any way possible to do this? I've been searching on here but haven't been able to find a solution.

Answer Source

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)

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download