rggplot2plotbar-chartstacked-bar-chart

Stacked barplot for a matrix with numbers as labels on the bars


I have a matrix which has 4 columns and 4 rows. But I am having a lot of troubles to put the numbers in the graph in an elegant way. Specifically, I want to have the numbers of the each part of the stacked bars to distinguish the percentages.

The matrix is this one, named as tabl.

3.89 4.97 8.56 7.17
35.67 42.73 51.68 50.09
48.30 43.48 34.95 38.24
12.14 8.82 4.81 4.50

And my current code to plot it is

nombres_comp <- c("Tac. \n Urb",
                  "Ven. \n Urb",
                  "Tac. \n Game",
                  "Ven. \n Game")

bp<-barplot(tabl,
        main = NULL,
        xlab = "(%)",
        ylab = NULL,
        axes = TRUE,
        horiz = TRUE,
        beside = FALSE,
        names.arg = nombres_comp,
        col = c("#487c82","#487c83", 
                "#81e0eb", "#b1ecf2")
        )
y <- tabl
text(bp+2,y,labels=as.character(y))

However, the output is putting the numbers in a strange place outside of the bars. I want them to be inside each place correctly identified in the barplot().

enter image description here

Also I would appreciate if someone beside solving this, could show me for completeness how to do this on ggplot2.


Solution

  • tabl <- as.matrix(read.table(text = "3.89   4.97    8.56    7.17
                                         35.67  42.73   51.68   50.09
                                         48.30  43.48   34.95   38.24
                                         12.14  8.82    4.81    4.50", header = F))
    
    nombres_comp <- c("Tac. \n Urb", "Ven. \n Urb",
                      "Tac. \n Game", "Ven. \n Game")
    
    bp<-barplot(tabl,
                main = NULL, xlab = "(%)", ylab = NULL,
                axes = TRUE, horiz = TRUE, beside = FALSE,
                names.arg = nombres_comp,
                col = c("#487c82", "#487c83", "#81e0eb", "#b1ecf2"))
    
    y <- apply(tabl/2 + rbind(rep(0, ncol(tabl)) , 
                              head(apply(tabl, 2, cumsum), -1)), 
               1, as.numeric)
    
    l <- as.character(apply(tabl, 1, as.character))
    
    text(bp,x = y , labels= l)
    

    Created on 2024-03-15 with reprex v2.0.2