user3022875 user3022875 - 2 months ago 29
R Question

Set ggplot2 label background color

I have this bar plot

group = c("A","A","B","B")
value = c(25,-75,-40,-76)
day = c(1,2,1,2)
dat = data.frame(group = group , value = value, day = day)
dat
ggplot(data=dat, aes(x=factor(group), y=value, fill=factor(day))) +
geom_bar( stat="identity", position="dodge")+
geom_label(aes(label =round(value,0),fill="white"),colour = "black", position= position_dodge(width=1))


I'd like the lables to be white backgroud with black font but when I add fill="white" the plot is incorrect. The labels do not have white background with black font.

notice here without the fill="white" the plot looks good. I just want to change label background and font

group = c("A","A","B","B")
value = c(25,-75,-40,-76)
day = c(1,2,1,2)
dat = data.frame(group = group , value = value, day = day)
dat
ggplot(data=dat, aes(x=factor(group), y=value, fill=factor(day))) +
geom_bar( stat="identity", position="dodge")+
geom_label(aes(label =round(value,0)),colour = "black", position= position_dodge(width=1))


# ALSO NOTE

If I move fill="white" outside the aes then the labels are not over the bars but stacked on one another. i.e. it negates the effect of position=position_dodge(width=1) and I need the labels over the bars

Thank you.

Answer

Make two changes:

  1. Move fill = factor(day) into aes() within the geom_bar
  2. Set group = factor(day) in your geom_label

As shown here:

ggplot(data=dat, aes(x=factor(group), y=value)) +
  geom_bar(aes(fill = factor(day)), stat="identity", position="dodge")+
  geom_label(aes(label =round(value,0), group = factor(day)),colour = "black", position= position_dodge(width=1))

enter image description here