设置ggplot2标签背景颜色

时间:2016-09-15 15:02:14

标签: r ggplot2

我有这个条形图

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))

我希望这些标签是黑色字体的白色背景但是当我添加fill="white"时,情节不正确。标签没有黑色字体的白色背景。

注意这里没有fill="white"情节看起来不错。我只想更改标签背景和字体

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)

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))

另请注意

如果我将fill="white"移到aes()之外,那么标签不会超过条形,而是堆叠在一起。即它否定了position=position_dodge(width=1)的效果,我需要标签上的标签

谢谢。

1 个答案:

答案 0 :(得分:4)

进行两项更改:

  1. fill = factor(day)移至aes()
  2. 中的geom_bar
  3. group = factor(day)
  4. 中设置geom_label

    如下所示:

    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