在堆叠条形图上居中文本标签

Centering text labels on stacked bar plots

条形图的颜色基于 'MaskID',在此代码中,我可以将 'MaskID' 名称制作成文本标签,但我希望名称以它们为中心相应的颜色。

你会怎么做?

p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + theme(axis.text.x = element_text(angle=90, vjust=-0.005))
p <- p + geom_text(aes(label = ifelse(y != 0, as.character(MaskID), ''), angle=90))

(还要考虑文本标签不会显示 y 值为 0 的条形)

     MaskID        x     y
0       ABC    Name1     0 
1       ABC    Name2     0  
2       ABC    Name3     1
3       ABC    Name4     0
..      ...      ...   ...
100     DEF    Name1     0
101     DEF    Name2     0
102     DEF    Name3     3
103     DEF    Name4     4
104     DEF    Name5     0

这是我正在构建的图表的一部分:

这似乎可行,尽管我认为它有点复杂。它使用 ggplot_build 提取描述条形位置的数据,找到它们的中点和适当的标签,然后添加文本。

## Make the graph (-the text parts)
p <- ggplot(df, aes(x, y))
p <- p + xlab("xlabel")
p <- p + ylab("ylabel")
p <- p + ggtitle("ylabel vs xlabel")
p <- p + geom_bar(stat="identity", aes(fill=MaskID))
p <- p + theme(axis.text.x = element_text(angle=90, vjust=-0.005))

## Get the bar data from ggplot
dd <- ggplot_build(p)[[1]][[1]]

## Get the y-values in the middle of bars
xy <- unique(dd[dd$y != 0, c("x", "y")])
dat <- with(xy, data.frame(
    x=x,
    y=unlist(sapply(split(y, x), function(z) diff(c(0, z))/2 + head(c(0, z), -1)))
))

## Get the labels
labels <- with(df[df$y!=0,], unlist(split(MaskID, x)))

## Add the text using the new xy-values and labels
p + geom_text(data=dat, aes(x, y), label=labels, angle=90)