1

I have a data frame with three columns:

  1. outcome: factor variable (with two rows)
  2. n: integer variable displaying the number of time the factor variable appears in the data frame
  3. freq: dbl variable displaying the frequency of the factor variable in the data set

    df <- data.frame(outcome = as.factor(c("Good", "Bad")), n = c(700, 300), freq = c(70, 30))

I use the following code to create a bar chart based on the frequency of my factor variable:

library(ggplot2)  

ggplot(df, aes(x=outcome, y=freq, fill=outcome)) + 
  geom_bar(stat="identity", width=.4) +
  geom_text(aes(label=paste0(freq,"%")), vjust=1.5, colour="white")

This code displays the frequency at the top each bar, something like this 70% enter image description here

I want to display both the frequency and the count on top of my bar chart. Something like: 70% (4532) With, if possible, a line break between the percentage and the count.

Any idea on how to achieve this?

zx8754
  • 52,746
  • 12
  • 114
  • 209
remif
  • 27
  • 2
  • 6
  • 2
    [How to make a great R reproducible example?](http://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) – zx8754 Oct 07 '15 at 07:55
  • 1
    How about changing `label` to `paste0(freq, "%\n(", n, ")")` – Axeman Oct 07 '15 at 08:11

1 Answers1

2
ggplot(df, aes(x=outcome, y=freq, fill=outcome)) + 
 geom_bar(stat="identity", width=.4) +
 geom_text(aes(label=paste0(freq, "%\n(", n, ")"), vjust=1.5, colour="white")

enter image description here

Axeman
  • 32,068
  • 8
  • 81
  • 94