设置ggplot2标签背景色

use*_*875 1 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))
Run Code Online (Sandbox Code Playgroud)

我希望标签为带有黑色字体的白色背景,但是当我添加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))
Run Code Online (Sandbox Code Playgroud)

还请注意

如果我移到fill="white"外面,aes()则标签不在条形图上,而是彼此堆叠。即它否定了效果,position=position_dodge(width=1)我需要在条形上贴标签

谢谢。

Dav*_*son 5

进行两项更改:

  1. 移动fill = factor(day)aes()geom_bar
  2. 设置group = factor(day)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))
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

  • @ user3022875将“ fill =“ green”`放置在aes之外,并将您的“ colour”更改为“ blue”。例如`geom_label(aes(label = round(value,0),group = factor(day)),fill =“ green”,color =“ blue”,position = position_dodge(width = 1))` (2认同)