R stacked bar graph plotting geom_text

后端 未结 2 593
野趣味
野趣味 2020-12-16 01:50

I\'m trying to plot a stacked bar graph in R using ggplot. I also want to include percentage in each piece of bars for that piece. I tried to follow the posts 1, 2, 3 but th

2条回答
  •  星月不相逢
    2020-12-16 01:59

    Here a solution using barchart from lattice.

    enter image description here

    library(latticeExtra)
    barchart(Percentage~Form|Sample_type*Sample_name,data=dat,
             groups =Position,stack=T,
             panel=function(...){
               panel.barchart(...)
               ll <- list(...)
               keep <- !is.na(ll$groups[ll$subscripts])
               x <- as.numeric(ll$x[keep])
               y <- as.numeric(ll$y[keep])
               groups <- as.numeric(factor(ll$groups)[ll$subscripts[keep]])
               for (i in unique(x)) {
                   ok <- x == i
                   ord <- sort.list(groups[ok])
                   pos <- y[ok][ord] > 0
                   nok <- sum(pos, na.rm = TRUE)
                   h <- y[ok][ord][pos]
                   panel.text(x = rep(i, nok),y = cumsum(h)-0.5*h,
                              label = h,cex=1.5)
                 }
             },
             auto.key = list(columns = 5), 
             par.settings = ggplot2like(n = 5),
             lattice.options = ggplot2like.opts())
    

提交回复
热议问题