Labeling with Percentage in R plot
Hi I have made this function that takes a table and prepare the label for a barplot
prepare_labels <- function(ft){
labs <- ft
labs <- paste(labs, "\n", sep="")
labs <- paste(labs, round(prop.table(ft)*100,2), sep="")
labs <- paste(labs, "%", sep="")
return(labs)
}
It actually works fine, but is there any better way to write that function, the above code looks ugly and I want to write beautiful code :-)
ex:
ft <- table(mydata$phone_partner_products)
prepare_labels(ft)
[1] "3752\n34.09%" "226\n2.开发者_Go百科05%" "2907\n26.41%" "1404\n12.76%" "1653\n15.02%"
[6] "1065\n9.68%"
Since the sep argument is the same for all the paste calls, then you can combine into a single one:
labs <- paste(ft,"\n",round(prop.table(ft)*100,2),"%",sep="")
Or, using ggplot2
:
ggplot(mtcars, aes(factor(cyl))) + geom_bar() + stat_bin(aes(label = paste(prop.table(..count..) * 100, "%", sep = "")), vjust = -0.2, geom = "text", position = "identity")
and get something like this:
alt text http://img532.imageshack.us/img532/8201/barplotwpct.png
Using sprintf
:
sprintf("%d\n%2.2f%%", ft, prop.table(ft)*100)
精彩评论