ggplot2 - geom_text

Hello Guys! I have the code below and i would like to use geom_text to put label above the corresponding bar. Could somebody help me? Thank you very much!

library(ggplot2)
library(tidyverse)
# Tibble
TB1 <-tribble(
  ~Codigo, ~Valor, ~Descricao, ~Categoria, ~Subcategoria, ~Grupo,
  1,      4,      "aaa",        "A",           "a",    "I",  
  2,     13,      "bbb",        "A",           "a",   "II",
  3,     24,      "ccc",        "A",           "b",   "II",
  4,     36,      "ddd",        "B",           "a",  "III",
  5,     55,      "eee",        "B",           "a",   " I", 
  6,     89,      "fff",        "B",           "c",   "II", 
  7,    113,      "ggg",        "B",           "d",   "II",
  8,    313,      "ggg",        "C",           "a",   "IV"
)

DADOS <- TB1 %>% group_by(Categoria, Subcategoria, Grupo) %>% summarise(Soma = sum(Valor))
DADOS %>%
  ggplot(aes(x = Subcategoria, y = Soma, fill = Grupo)) +
  geom_bar(stat = "identity", position = position_dodge(preserve = 'single'))+
  geom_text(aes(label=Soma), position=position_dodge(width = 0.9), vjust=-0.5, size=3.5)

Try with position_dodge2 and specifying the width in the geom_bar as well:

DADOS %>%
  ggplot(aes(x = Subcategoria, y = Soma, fill = Grupo, label = Soma)) +
  geom_bar(stat = "identity", position = position_dodge2(width = 0.9, preserve = 'single')) +
  geom_text(position = position_dodge2(width = 0.9, preserve = "single"), vjust=-0.5, size=3.5)

image

1 Like

It Works!! Thank you very much!!

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.