-1

I want to add the actual numbers above each bar. I tried this but wasn't working. How should I fix that? MP1 is an SPSS file, TBI and mp_1 are mutated factors.

ggplot(MP1) +
  geom_bar(aes(x=TBI), fill=mp_1))+
  geom_text(aes(label=count), vjust=1.5, colour="white", size=3.5)
phalteman
  • 3,442
  • 1
  • 29
  • 46
Roxana
  • 1
  • 2
  • 3
    Why isn't it working? What are you seeing and what do you want to see? What else have you tried? And if you can provide a bit of your data (10 or 20 rows at most), that will help others test their solutions. – phalteman Jul 27 '21 at 23:11

1 Answers1

0

From what I can see you have some typos/syntax issues, e.g. an extra ")" at the end of the geom_bar() line, and no stat = "count" in your geom_text(). Here is a reproducible example using the mtcars dataset which illustrates a potential solution:

library(ggplot2)

ggplot(mtcars) +
  geom_bar(aes(x = cyl)) +
  geom_text(stat = "count", aes(x = cyl, label = ..count..), 
            vjust = 1.5, colour = "white", size = 3.5)

Created on 2021-07-28 by the reprex package (v2.0.0)

I can't test the solution out with your data as you haven't provided any (please see How to make a great R reproducible example), however my guess for your situation is:

ggplot(MP1) +
  geom_bar(aes(x=TBI), fill="dodgerblue"))+
  geom_text(stat = "count", aes(x=TBI, label=..count..), vjust=1.5, colour="white", size=3.5)

In order to create a stacked barplot:

library(ggplot2)
ggplot(mtcars, aes(fill = factor(gear), x = factor(carb))) + 
  geom_bar(position = "stack") + 
  geom_text(stat = "count", aes(label = ..count..),
            position = position_stack(vjust = 0.5))

Created on 2021-07-28 by the reprex package (v2.0.0)

jared_mamrot
  • 22,354
  • 4
  • 21
  • 46