5

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

zx8754
  • 52,746
  • 12
  • 114
  • 209
anonymous
  • 815
  • 3
  • 13
  • 21

1 Answers1

5

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

Rorschach
  • 31,301
  • 5
  • 78
  • 129
  • Thanks! The text labels are on the middle of the bar now... but instead of putting the MaskID names as the labels, it put's the y-value numbers of how high the bars are. – anonymous Jul 28 '15 at 16:44
  • What do you mean by 'labels'? The names in MaskID consist of numbers and characters+numbers – anonymous Jul 28 '15 at 17:44
  • Oh, sorry! And the variable 'labels' is a list of the text names follow by their corresponding number. So for example, Name3 would have a number under it and Name4 would have another number under it, etc. – anonymous Jul 28 '15 at 18:14
  • 1
    @raychul when you write `class(df$x)` do you get `factor`? Convert that to character, `as.character(dt$x)` – Rorschach Jul 28 '15 at 18:25