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.
EDIT: I have figured out that using label = deparse(labs) uses all of the labels.