Search code examples
rggplot2bar-chartgeom-text

How to add a frequency or number on scalebar of stacked barplot using geom_text?


I'm a newbie for using Rstudio, so I've some problems I want to ask.

I want to make my scalebar for species composition in 10 sites, and add the number inside the scalebar.

The result like this.

species composition sufrahaislamia

I want to put the frequency number of species composition inside the scale bar. I've been tried to put code of geom_text, but the result is not appropriate at all.

I hope there's an answer to fix this. Thank you so much.

Here is my data, also the coding that I run in R.

data <- as.matrix(data.frame(Bng = c(0, 0, 0, 41, 0, 9, 6, 25, 11, 2, 5, 7), 
                             Krs = c(0, 25, 0, 82, 0, 0, 0, 0, 23, 0, 0, 0),
                             Bny = c(0, 0, 0, 0, 0, 0, 0, 23, 16, 0, 10, 0),
                             Kmb = c(1, 0, 0, 0, 20, 0, 0, 25, 8, 1, 0, 0),
                             Sgk = c(0, 0, 0, 18, 0, 2, 0, 11, 0, 0, 0, 0),
                             Lwb = c(1, 0, 2, 73, 0, 5, 0, 7, 5, 0, 0, 0),
                             Lws = c(0, 0, 0, 4, 0, 0, 0, 4, 0, 4, 1, 0),
                             Krp = c(0, 0, 0, 115, 0, 0, 2, 0, 2, 0, 0, 0),
                             Hrt = c(4, 0, 0, 0, 2, 22, 0, 7, 4, 2, 3, 0),
                             Gmb = c(0, 2, 0, 42, 2, 0, 0, 1, 6, 4, 3, 0)))
rownames(data) <- c("Cbr", "Csx", "Rax", "Hdd", "Hlv", "Mst", "Mps", "Mbr", "Rfs", "Rbn", "Rct", "Rps")
data 
barplot(data)
barplot(prop.table(data, 2))```
library(reshape2)
data_long <- as.data.frame(data)
data_long$subgroup <- rownames(data_long)
data_long <- melt(data_long, id.vars = "subgroup")
library(ggplot2)
ggp <- ggplot(data_long,           
              aes(x = variable,
                  y = value,
                  fill = subgroup)) +
  geom_bar(position = "fill", stat = "identity")+
  theme_bw()+
  scale_fill_grey()
ggp                                

ggp +                              
  scale_y_continuous(labels = scales::percent_format())

Solution

  • You may try

    library(dplyr)
    data_long %>%
      group_by(subgroup) %>%
      mutate(key = sum(value),
             value = value/sum(value)
             ) %>%
      filter(value != 0) %>%
      ggplot(aes(x = variable,
               y = value,
               fill = subgroup)) +
      geom_bar(position = "fill", stat = "identity")+
      theme_bw()+
      scale_fill_grey() +                              
      scale_y_continuous(labels = scales::percent_format()) +
      geom_text(aes(label = value * key), position = position_fill(vjust = .5))
    

    enter image description here