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

5
条形图的颜色基于'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

这是我正在构建的图表的一部分: enter image description here

1
一个可重现的例子会很好。 - mathematical.coffee
上面发布了一个基本示例,展示了我的数据大致的样子! - anonymous
1
通过可重现的例子,我指的是我们可以复制的内容。 - mathematical.coffee
1个回答

5

这似乎是可行的,尽管我认为它有点复杂。它使用 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)

enter image description here


谢谢!现在文本标签位于条形图的中间...但是它并没有将MaskID名称作为标签,而是将条形的高度值作为标签。 - anonymous
“labels”是什么意思?MaskID中的名称由数字和字符+数字组成。 - anonymous
您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - anonymous
1
@raychul 当你写 class(df$x) 时,你得到的是 factor 吗?将其转换为字符型,as.character(dt$x) - Rorschach

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接