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() 在处理文本几何时非常不稳定......)。