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

ano*_*ous 5 format plot r bar-chart ggplot2

条形图的颜色基于'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))
Run Code Online (Sandbox Code Playgroud)

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

     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
Run Code Online (Sandbox Code Playgroud)

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

在此输入图像描述

pic*_*ick 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)
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述