0

I'm trying to align the percent frequency of each bar in my clustered bar chart. Right now, my chart looks like this:

Rplot01

Here's the code as well:

ggplot(graph_data, aes(x, Freq)) +
    geom_bar(aes(fill = Pref), position = 'dodge', stat = 'identity') +
    geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))),
              hjust = -0.25) +
    labs(list(x = attr(graph_data, 'seg_label'),
              y = 'Frequency',
              title = paste('Q:', attr(graph_data, 'question')))) +
    scale_y_continuous(limits = c(0, 1.2 * max(graph_data$Freq))) +
    guides(fill = F) +
    coord_flip() +
    annotate("text", x = Inf, y = Inf,
             label = paste0("N = ", sum(graph_data$Freq)),
             hjust = 1.5, vjust = 1.5)

I think the issue can be solved on this snippet of code, but I'm not sure how:

geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))), hjust = -0.25)

Any help would be greatly appreciated!

Edit: Here's a sample of my data's structure as well:

df <- data.frame(x = rep(c('1824', '2534', '3544'), 3),
                 Pref = rep(c('low', 'neutral', 'high')),
                 Freq = 1:9 * 10)
989
  • 12,579
  • 5
  • 31
  • 53
nev
  • 297
  • 3
  • 13
  • 2
    Possible duplicate of [Position geom\_text on dodged barplot](http://stackoverflow.com/questions/6017460/position-geom-text-on-dodged-barplot) – aosmith Jun 10 '16 at 14:23
  • Thanks for your reply. I think the feature on that post is depreciated - I couldn't recreate it with any examples I tried. The post is about 5 years old, so I think it's a likely explanation if I didn't make a mistake. – nev Jun 10 '16 at 14:33
  • Fixed it! The aesthetic parameter `fill` wasn't being passed into the geom_text function. I included all my aesthetics in the initial ggplot declaration to fix it, like this `ggplot(graph_data, aes(x = x, y = Freq, fill = Pref)` – nev Jun 10 '16 at 14:38
  • Here is another dupe that might be a bit more up-to-date: http://stackoverflow.com/questions/30634148/issue-with-geom-text-when-using-position-dodge. – aosmith Jun 10 '16 at 14:53

1 Answers1

0

As mentioned in the comments I think this is a duplicate of Position geom_text on dodged barplot.

But I did it now, so I'll include the code.

ggplot(df, aes(x, Freq, fill = Pref)) +
    geom_bar(position = 'dodge', stat = 'identity') +
    geom_text(aes(label = sprintf("%.0f%%", round(Freq/sum(Freq) * 100))),
          position = position_dodge(width = 0.9), hjust = -0.25) +
    labs(list(x = attr(df, 'seg_label'),
              y = 'Frequency',
              title = paste('Q:', attr(df, 'question')))) +
    scale_y_continuous(limits = c(0, 1.2 * max(df$Freq))) +
    guides(fill = F) +
    coord_flip()

You need to put fill in the original aes so the that geom_text knows which label to dodge by which amount.

enter image description here

Community
  • 1
  • 1
timcdlucas
  • 1,334
  • 8
  • 20