1

I have some data:

my_data = data.frame(Grade = rep(c("U", "B", "S", "E"), 3), 
Locality = rep(c("London", "Kent", "Dover"), 4), 
Freq = c(0,0,46,31,0,2,41,28,0,1,21,41), 
n = c(77,77,77,77,71,71,71,71,63,63,63,63), 
Percentage = c(0,0,59.74,40.26,0,2.82,57.75,39.44,0,1.59,33.33,65.08))

I want to plot this using ggplot2 and add the percentage as text above the bars. My current function looks something like this (I've kept it minial for purposes of demonstration):

my_fn = function(data, x, y, z_group, bar_text = T){
p = ggplot(data, aes_string(x = x, y = y))
p = p + geom_bar(aes_string(fill = z_group), position = "dodge", stat = "identity", colour = "black")
if (bar_text == T){
labs = replace(data[[y]], data[[y]] == 0, "")
p = p + geom_text(aes_string(label = labs, x = x, y = y), position = position_dodge(width = 0.9), vjust = -0.5)
}
plot(p)
}

my_fn(my_data, x = "Grade", y = "Percentage", z_group = "Locality")

The trouble I am having with this is that it puts the labs information all over the middle bar and it only includes the first non-zero value.

Imgur

EDIT: I have figured out that using label = deparse(labs) uses all of the labels.

nathaneastwood
  • 3,664
  • 24
  • 41
  • I recommend you to have a look of [this link](http://stackoverflow.com/questions/10112587/re-alignment-of-numbers-on-the-individual-bars-with-ggplot2). – jazzurro Sep 04 '14 at 11:52

1 Answers1

2

Here is the fixed code; I've added the group aesthetic and labs should be included as column in the data frame:

my_fn <- function(data, x, y, z_group, bar_text=TRUE) {

  data$labs <- replace(data[[y]], data[[y]] == 0, "")
  p <- ggplot(data, aes_string(x=x, y=y, group=z_group))
  p <- p + geom_bar(aes_string(fill=z_group), position="dodge",
                    stat="identity", colour="black")

  if (bar_text == TRUE) {
    p <- p + geom_text(aes_string(label="labs"),
                       position=position_dodge(width=0.9), vjust=-0.5)
  }
  plot(p)
}

my_fn(my_data, x="Grade", y="Percentage", z_group="Locality")

plot

rcs
  • 67,191
  • 22
  • 172
  • 153