0

I am trying to create a bar plot of the following data frame:

df <- structure(list(HCT_range = c("Low", "Low", "Low", "Low", "Low", 
"Low"), HG1_range = c("High", "High", "Normal", "High", "High", 
"Normal"), HG2_range = c("High", "Normal", "High", "High", "Normal", 
"High"), n = c(17L, 54L, 66L, 15L, 61L, 60L), Type = c("LHH", 
"LHN", "LNH", "LHH", "LHN", "LNH"), File = c("a", "a", "a", "b", 
"b", "b"), Perc = c(0.0387, 0.123, 0.1503, 0.0342, 0.1389, 0.1366
 )), row.names = c(NA, -6L), class = c("tbl_df", "tbl", "data.frame"
))

I am trying to create a dodged bar plot with the following command:

ggplot(data = df, aes(x = Type, y = n)) +
  geom_col(aes(fill = File), position = position_dodge(width = 0.9)) +
  geom_text(aes(label = Perc), position = position_dodge(0.9))

But for some reason, the test is not dodged but stacked - despite the specific position call.

Any ideas?

Omry Atia
  • 2,411
  • 2
  • 14
  • 27
  • 2
    Add a `group` `aes` to `geom_text` or `ggplot`, as described in _several examples the help text_ `?geom_text`. Moving `fill = File` to `aes` in `ggplot` also works. – Henrik Oct 25 '18 at 07:44
  • I have added: ggplot(data = DF, aes(x = Type, y = n)) + geom_col(aes(fill = File), position = position_dodge(width = 0.9)) + geom_text(aes(label = Perc, group = 1), position = position_dodge(0.9)) - it didn't change anything – Omry Atia Oct 25 '18 at 07:55

1 Answers1

4

You just need to specify what your bars represent with the fill argument. Otherwise ggplot doesn't know where to place the text. Does this solve your problem?

ggplot(data = df, aes(x = Type, y = n, fill=File)) +
      geom_col(aes(fill = File), position = position_dodge(width = 0.9)) +
      geom_text(aes(label = Perc), position = position_dodge(0.9))

You may also have a look at this question: Position geom_text on dodged barplot

alex_555
  • 1,092
  • 1
  • 14
  • 27