I asked a similar question to this in a previous post, and this code works when all the x-axis ticks are in sorted alphabetical order. The colors of the bar plot are based off of 'MaskID'. However, when I change the order of the x-axis ticks, the 'MaskID' text labels that I want on the stacked bar plot do not change according to their corresponding colors.
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, hjust=1))
df$x <- as.character(df$x)
dd <- ggplot_build(p)[[1]][[1]]
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)))
))
labels <- with(df[df$y!=0,], unlist(split(MaskID, x)))
p <- p + geom_text(data=dat, aes(x, y), label=labels, angle=90)
Here's a basic example of how my data is formatted:
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 a sample graph (posted by @nongkrong from my previous question):
Let's say instead of my ticks being in alphabetical order from Name1 to Name5, I want my ticks to be in any arbitrary order. Example: Name2, Name1, Name4, Name3, Name5
When changing the tick order (for a bigger data set), how would you center the text labels if the order is not alphabetical?