2

I would be very grateful for some help with ggplot2. I cannot seem to be able to vertically center the labels on the bars.

Here's the code:

library(ggplot2)

Group.id <- c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3)
Type.id <- c("a", "b", "c", "d", "a", "b", "c", "d","a", "b", "c", "d")
Value <- c(4000, 3200, 9529, 3984, 7504, 1244, 8960, 1865, 1100, 1100, 0, 0)
df <- data.frame(Group.id, Type.id, Value)


ggplot(df, aes(x = Group.id, y = Value, label = Value)) +
  geom_bar(stat = "identity", aes(fill = Type.id)) +
  scale_fill_manual(values=c("#00AF50", "#64A70B", "#F2A900", "#C30C3E"), labels = rev(unique(df$Type.id))) +
  geom_text(position = position_stack(vjust = .5), color = "#FFFFFF") 

And here's the result: Barplot without centered labels

It works with small values, but for some reason it is not centered with bigger values. Any suggestion?

iLib
  • 23
  • 4

1 Answers1

3

Put fill = Type.id inside the first aes() call:

ggplot(df, aes(x = Group.id, y = Value, label = Value, fill = Type.id)) +
  geom_bar(stat = "identity") +
  scale_fill_manual(values=c("#00AF50", "#64A70B", "#F2A900", "#C30C3E"), labels = rev(unique(df$Type.id))) +
  geom_text(position = position_stack(vjust = .5), color = "#FFFFFF") 

enter image description here

dave-edison
  • 3,666
  • 7
  • 19