Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Centering text labels on stacked bar plots

The colors of the bar plot are based off of 'MaskID' and in this code I am able to make the 'MaskID' names into text labels, but I want the names to be centered on their corresponding colors.

How would you do this?

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))

(Also consider that the text labels do not show for bars with 0 y-values)

     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

Here's part of the graph that I'm building:

enter image description here

like image 841
anonymous Avatar asked Jul 28 '15 00:07

anonymous


1 Answers

This seems to work, although its a bit complex for this I think. It uses ggplot_build to pull out the data describing the bar locations, finds their midpoints and the appropriate labels, then adds the text.

## 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

like image 89
Rorschach Avatar answered Oct 16 '22 05:10

Rorschach