更改一个堆叠条的字体颜色

Change font color of one stacked bar

如何仅更改顶部堆积条的字体颜色?

您需要从scale_fill_中选择一个函数,这里是一个列表

 [1] "scale_fill_binned"     "scale_fill_brewer"     "scale_fill_continuous"
 [4] "scale_fill_date"       "scale_fill_datetime"   "scale_fill_discrete"  
 [7] "scale_fill_distiller"  "scale_fill_fermenter"  "scale_fill_gradient"  
[10] "scale_fill_gradient2"  "scale_fill_gradientn"  "scale_fill_grey"      
[13] "scale_fill_hue"        "scale_fill_identity"   "scale_fill_manual"    
[16] "scale_fill_ordinal"    "scale_fill_steps"      "scale_fill_steps2"    
[19] "scale_fill_stepsn"     "scale_fill_viridis_b"  "scale_fill_viridis_c" 
[22] "scale_fill_viridis_d" 

如果您想手动设置它们,请使用 scale_fill_manual,其中包含颜色矢量,然后将它们添加到您的 ggplot 代码中

例子

代码

mtcars %>% 
  count(cyl,gear = as.factor(gear)) %>% 
  ggplot(aes(cyl,n,fill = gear))+
  geom_col(position = "fill")+
  scale_fill_manual(values = c("red",'purple',"darkgoldenrod2"))

输出

OP,以后尽量提供一个完整的有代表性的例子。无论如何,这里是你的情节几乎复制:

library(ggplot2)

df <- data.frame(
  value=c(12, 17, 14, 46, 41, 66, 14, 14, 14, 27, 28, 7),
  category=rep(LETTERS[1:4], each=3),
  gender=rep(c("Male", "Female", "Other"), 4)
)

ggplot(df, aes(x=gender, y=value)) +
  geom_col(aes(fill=category), position=position_stack(vjust=0.5, reverse = TRUE)) +
  geom_text(
    aes(label=paste(value,"%")), size=5,
    position=position_stack(vjust=0.5)) +
  scale_fill_viridis_d()

要根据标准应用不同的颜色,您可以直接将该标准指定到 geom_text() 中的 color= 审美。在这里,我将使用 ifelse() 函数来定义何时更改颜色。这可行,但这样做意味着我们正在即时计算,而不是将结果映射到我们的原始数据。由于选择颜色的方式 绑定到我们数据中的列,因此 您需要在 aes() 函数之外定义此颜色。 因此,geom_text() 函数相应修改:

geom_text(
    aes(label=paste(value,"%")), size=5,
    color=ifelse(df$category=="A", 'white', 'black'),
    position=position_stack(vjust=0.5))

再次注意 - 我在 aes() 之外定义了 color=。另一种方法是将文本颜色映射到 category,然后使用 scale_color_manual() 手动定义颜色。实际上,在 aes() 之外使用 ifelse() 更直接。 (另外,position_stack() 在处理文本几何时非常不稳定...)。