Sophia Sophia - 7 months ago 141
R Question

Add count labels to clustered bar graph ggplot2

I tend to struggle with adding labels to bar graphs. I am trying to add count labels next to each bar in this graph, but the numbers are not placed in the right spot:

bargraph

Here is my data (a subset of a bigger dataset):

County Group Plan1 Plan2
County1 Group3 597 513
County2 Group3 182 130
County3 Group3 180 126
County4 Group3 266 284
County5 Group3 258 171
County6 Group3 159 71
County7 Group3 187 157
County8 Group3 101 84


I tried to use geom_text() suggestions from other posts, but kept getting similar results.

Code:

df.g <- gather(df, key=`Plan Type`, value=value, -County, -Group)

ggplot(df.g[df.g$Group == "Group3", ],
aes(County, value)) +
geom_bar(aes(fill = `Plan Type`),
stat = "identity", colour = "black", position = "dodge") +
scale_fill_brewer(palette = "Set2") +
ggtitle("Enrollees per Plan by County") +
theme(plot.title = element_text(hjust=0.5)) +
coord_flip() +
geom_text(aes(x = County, y = value, label = value,
hjust = ifelse(sign(value) > 0, 1, 0)),
position = position_dodge(width = 1))


How can I add count labels correctly to this graph? Thank you for any advice/suggestions!

Answer Source

Try this:

library(tidyr)

df.g <- gather(df, 
#personal preference: avoid using variable names with spaces; looks cleaner that way.
               key = Plan.Type, 
               value = value, 
               -County, -Group)

ggplot(filter(df.g, Group == "Group3"),
       aes(x = County, y = value, 
           fill = Plan.Type,
           label = value)) +
  geom_col(position = "dodge") +
  geom_text(position = position_dodge(width = 0.9),
            hjust = 0) +
  # + other title / theme options
  coord_flip()

plot

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download