r - 设置ggplot2标签背景色

标签 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. fill = factor(day) 移动到 geom_bar 内的 aes()
  2. geom_label 中设置 group = factor(day)

如图所示:

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

关于r - 设置ggplot2标签背景色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39514394/

相关文章:

r - R&xml2:通过特定的文本值定位元素,将所有子值存储在data.frame中

r - ggplot2 : Error in barplot - X axis displayed improperly

r - 如何在图例ggplot2中添加多个标题?

r - 如何提取 ggplot2 使用的坐标单位?

r - 从列表转换为数字

r - 聚合随机采样的列以迭代更大的 bin 大小

r - 将函数列表应用于 R 中的单个参数

r - 如果列采用特定值,则分配新变量

r - 如何删除 ggplot2 中日期 Axis 上的间隙

r - "Error: Don' 在 R 中保存主题格式时不知道如何将 RHS 添加到主题对象