Search code examples
rggplot2geom-bargeom-text

R: Display character or categories on a stack bar


I am trying to add the category and percent to each level in a stack bar, example:

Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Data      <- data.frame( Category)

p= ggplot(Data,aes(x=factor(""),fill=factor(Category)))+
  geom_bar(position="fill")+
  geom_text(aes(label=scales::percent(..count../sum(..count..))),   stat='count',position=position_fill(vjust=0.5))

This produce this graph: stack bar result

But I try to get this graph whit this command, but I failed

Graph expected Graph expected

p=ggplot(Data,aes(x=factor(""),fill=factor(Category)))+
  geom_bar(position="fill")+
  geom_text(aes(label=scales::percent(..count../sum(..count..))), stat='count',position=position_fill(vjust=0.5))

  p + geom_text(data=Data, aes(x=factor(""),label = Category),  position=position_fill(vjust=0.5))

Solution

  • You were well on your way to getting the desired text, I think if you add the stat = "count" and adjust the vjust a bit you would have what you wanted.

    library(ggplot2)
    Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
    Data      <- data.frame( Category)
    
    ggplot(Data,aes(x=factor(""),fill=factor(Category)))+
      geom_bar(position="fill")+
      geom_text(aes(label=scales::percent(..count../sum(..count..))),   
                stat='count',position=position_fill(vjust=0.5)) +
      geom_text(aes(label = Category), fontface = "bold",
                stat = "count", position = position_fill(vjust = 0.25))
    

    Created on 2021-01-09 by the reprex package (v0.3.0)