0

I am trying to add asterisks (*) to the bars of a bar chart to indicate the significance of a value using ggplot2. There are other answers to similar questions2, but I wasn't able to figure out which arguments to add to geom_text().

Here is data frame 'data':

group <- c(rep(1, 3), rep(2, 3), rep(3, 3), rep(4, 3))
n <- runif(12, 0, 25)
sig <- c("*", rep("", 11))
cluster <- rep(c("1", "2", "3"), 4)

data <- data.frame(group, n, sig, cluster)

I made a plot with an asterisk using geom_text(), but instead of being over the first bar, it is over the first group:

plot <- ggplot(data, aes(x = group, y = n, fill = cluster)) + 
    geom_bar(position = "dodge", stat = "identity", width = .75) + 
    geom_text(aes(label = sig))

enter image description here

How can I align the asterisk to be directly above the first bar?

Community
  • 1
  • 1
Joshua Rosenberg
  • 4,014
  • 9
  • 34
  • 73
  • 1
    You need to `dodge` the `geom_text` as well, and set an explicit `width` of the dodging. "dodge" only is is not the same in absolute units for a bar and the text. You will often find e.g. `dodge <- position_dodge(width = 0.7)`; `bla bla bla + geom_bar(position = dodge) + geom_text(position = dodge)` – Henrik Aug 05 '15 at 21:05
  • See e.g. the examples of [`geom_errorbar`](http://docs.ggplot2.org/current/geom_errorbar.html): "Because the bars and errorbars have different widths we need to specify how wide the objects we are dodging are: `dodge <- position_dodge(width=0.9)`. The same applies to your bars and text. – Henrik Aug 05 '15 at 21:16
  • Thanks much for the help. Tried that. Any idea why the error `Error: Aesthetics must either be length one, or the same length as the dataProblems:dodge` is being returned? – Joshua Rosenberg Aug 05 '15 at 21:25
  • Oops, had `position` inside aes(), rather than on the next line. Worked. – Joshua Rosenberg Aug 05 '15 at 21:30
  • 1
    `ggplot(data, aes(x = group, y = n, fill = cluster)) + geom_bar(position = "dodge", stat = "identity", width = .75) + geom_text(aes(label = sig, y = n+.5, group=cluster), size = 3, position = position_dodge(width=0.9))` – Tyler Rinker Aug 05 '15 at 21:32

0 Answers0