Tom Martens
Tom Martens

Reputation: 776

label a dodged bar chart

Maybe it's because of the dark outside, but I can't get this

Position geom_text on dodged barplot

to work on my fairly simple dataframe

fs <- data.frame(productcategory=c("c2","c2"), product=c("p4", "p5"), ms1=c(2,1))

plot <- ggplot(data=NULL)
plot + 
    geom_bar(data=fs, aes(x=productcategory, y=ms1, weight=ms1, fill=product),stat="identity", position="dodge") + 
    geom_text(data=fs, aes(label = ms1,  x = productcategory, y=ms1+0.2), position=position_dodge(width=1)))

My plot still shows the labels in the "middle" of the product category and not above of the proper product.

Looks like this even it seems very simple, but I'm totally stuck on this

So any hints are very much appreciated how to get labels above the proper bars.

Tom

Upvotes: 0

Views: 995

Answers (1)

Marius
Marius

Reputation: 60060

Because you have the aesthetics defined for each geom individually, geom_text isn't picking up on the fact that you're subdividing the x variable productcategory by the fill variable product.

You can get the graph you want by adding fill=product to the aes() call for geom_text, or you can try to define as many aesthetics as possible in the original ggplot() call, so that all the geoms pick up on those aesthetics automatically and you only have to define them if they're specific to that particular geom.

plot2 <- ggplot(data=fs, aes(x=productcategory, y=ms1, fill=product)) +
  geom_bar(stat="identity", position="dodge") +
  geom_text(aes(label=ms1, y =ms1 + 0.2), position=position_dodge(width=1))
print(plot2)

Upvotes: 4

Related Questions