Friday, 15 February 2013

r - insert labels in proportional bar chart with ggplot2 and geom_text -



r - insert labels in proportional bar chart with ggplot2 and geom_text -

i trying insert labels proportional barchart: 1 label per segment, text percentage of each segment. help of thothal managed this:

var1 <- factor(as.character(c(1,1,2,3,1,4,3,2,3,2,1,4,2,3,2,1,4,3,1,2))) var2 <- factor(as.character(c(1,4,2,3,4,2,1,2,3,4,2,1,1,3,2,1,2,4,3,2))) info <- data.frame(var1, var2) dat <- ddply(data, .(var1), function(.) { res <- cumsum(prop.table(table(factor(.$var2)))) data.frame(lab = names(res), y = c(res)) }) ggplot(data, aes(x = var1)) + geom_bar(aes(fill = var2), position = 'fill') + geom_text(aes(label = lab, x = var1, y = y), info = dat)

i have labels percentage of each level, , not level name.

any help appreciated!

you telling geom_text utilize var2 y variable. in fact as.numeric(data$var2), translates range of 1-4. however, barplot uses cumulative percentages.

hence have calculate these positions before:

library(ggplot2) library(plyr) # convenience var1 <- factor(as.character(c(1,1,2,3,1,4,3,2,3,2,1,4,2,3,2,1,4,3,1,2))) var2 <- factor(as.character(c(1,4,2,3,4,2,1,2,3,4,2,1,1,3,2,1,2,4,3,2))) info <- data.frame(var1, var2) dat <- ddply(data, .(var1), function(.) { res <- cumsum(prop.table(table(factor(.$var2)))) # re-factor utilize used levels res2 <- prop.table(table(factor(.$var2))) # re-factor utilize used levels data.frame(lab = names(res), y = c(res), lab2 = c(res2)) }) ggplot(data, aes(x = var1)) + geom_bar(aes(fill = var2), position = 'fill') + geom_text(aes(label = round(lab2, 2), x = var1, y = y), info = dat)

this places labs @ end of each bar. if want have them offset, should play arround in creation of dat.

r ggplot2

No comments:

Post a Comment