1
votes

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): enter image description here

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?

1

1 Answers

1
votes

This should just be reordering the data before getting the labels. Try this,

## Reorder bars as in the example
df$x <- factor(df$x, levels=paste0("Name", c(2:1,4:3,5)))

## This is all the same
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))
dd <- ggplot_build(p)[[1]][[1]]

## *** Remove the part about converting to character ***

## The same
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)))
))

## Order by factor
df <- df[order(df$x), ]
labels <- with(df[df$y!=0,], unlist(split(as.character(MaskID), x)))

p <- p + geom_text(data=dat, aes(x, y), label=labels, angle=90)
p

enter image description here