简体   繁体   中英

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)
DT
ggplot(DT, aes(Name, Total, fill=Name)) + 
        geom_bar(position="stack",stat="identity")

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM