2

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!

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.