R: Display character or categories on a stack bar

Viewed 35

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))
2 Answers

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)

Another option to achieve the desired result would be to make use of ggtext::geom_richtext and a bit of glue:

library(ggplot2)

Year      <- c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category  <- c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <- c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data      <- data.frame(Year, Category, Frequency)

my_lab <- function(x, y) {
  glue::glue("{scales::percent(x / sum(x))}<br><br><b>{y}</b>")
}

ggplot(Data,aes(x=factor(""), fill=factor(Category)))+
  geom_bar(position="fill")+
  ggtext::geom_richtext(aes(label = my_lab(..count.., ..fill..)), stat='count', label.color = NA, position=position_fill(vjust=0.5))

Related