geom_text 的颜色变化给出了完全不同的颜色然后要求

Changing of color for geom_text gives completely different color then called for

我想为我的 ggplot2 条添加标签并更改标签的颜色。反正我做不到。

我的数据集(已简化)大致采用以下格式:

data$value <- runif(27, min=10, max=60)
data$A <- factor((rep(1:3, each=9)))
data$B <- factor((rep(1:9, each=3)))
data$variable <- factor(rep(rep(1:3),9))


情节是这样的:

three <- c(pink="#BD1550",dark="#490A3D",blue1="#0b6fa1",white="#FFFFFF", "#FFFFFF")
 m<-  data %>% group_by(A, variable) %>% summarise(mean=mean(value), sd=sd(value)) %>% 
             ggplot(aes(x=A,fill=variable)) +
             geom_col(aes(y=mean),position="stack")+
             geom_text(aes(label=round(mean,digits=2),y=mean, colour="white")
                          ,size=3, show.legend = F, position = position_stack(vjust = 0.5))+
             scale_fill_manual(values=three) + theme(legend.position="right")

现在,对于 geom_text 中的颜色,我已经尝试过:

  1. 颜色="white"
  2. 拼颜色或颜色
  3. 颜色="#FFFFFF"
  4. 颜色=c("#FFFFFF")
  5. 颜色 = 4
  6. 颜色=白色
  7. one <- c("#FFFFFF") 然后 color = one

不同的解决方案为每个标签提供不同的颜色,粉色、橙色、绿色、蓝色来自我的字符串 'three',但永远不会给我白色。我也试过让它变成不同于白色的颜色,但不知何故我无法控制它给我的颜色。

我没有收到任何错误消息。

我开始运行没主意了。有人有解决方案吗?

问题是您正在 "white" 映射 aes() 中的色彩审美。这样 ggplot 认为你想在颜色美学上映射一个变量,即 "white" 不被解释为颜色的名称。相反,ggplot 只是从其默认调色板中选择颜色,即 "red"。只需将颜色作为参数传递给 aes() 之外的 geom_text。或者使用 scale_color_manual 设置调色板。 (; 试试这个:

library(ggplot2)
library(dplyr)

set.seed(42)

data <- data.frame(
  value = runif(27, min=10, max=60),
  A = factor((rep(1:3, each=9))),
  B = factor((rep(1:9, each=3))),
  variable = factor(rep(rep(1:3),9))  
)

three <- c(pink="#BD1550",dark="#490A3D",blue1="#0b6fa1", white="#FFFFFF", "#FFFFFF")
m <-  data %>% 
  group_by(A, variable) %>% 
  summarise(mean=mean(value), sd=sd(value)) %>% 
  ggplot(aes(x=A, fill=variable)) +
  geom_col(aes(y = mean),position="stack")+
  geom_text(aes(label = round(mean, digits=2), y=mean), colour="white"
            ,size=3, show.legend = F, position = position_stack(vjust = 0.5))+
  scale_fill_manual(values=three) + theme(legend.position="right")

m

reprex package (v0.3.0)

于 2020-04-14 创建