[R] need help in customising function in stat_summary function ggplot2

Indhira, Anusha Anusha.Indhira at controlsdata.com
Thu Oct 20 10:25:50 CEST 2016


I would like to print percentage of points in a group which are greater than median value in boxplot. I have tried below code but it always prints zero in the graph. Can you let me know, how to modify code to get desired result?

perc.greaterthan.median <- function(x){
  cnt = 0
  for(i in 1:length(x)){
   ifelse(x[i] > median(x),cnt+1,cnt)
  return(c(y = median(x)*1.7, label = round((cnt/length(x))*100,2)))

ggplot(st_chg_51, aes(x=factor(st_dv), P3))+ #label=rownames(st_chg_51))) +
  geom_boxplot(fill = "grey80", colour = "#3366FF") +
  stat_summary(fun.data = perc.greaterthan.median, geom = "text", fun.y = median) +
  theme_bw()+theme(axis.text = element_text(angle = 90, hjust = 1))

Why does cnt in the function doesn't get incremented in the loop?


This e-mail (including attachments) contains contents owned by Rolls-Royce plc and its subsidiaries, affiliated companies or customers and covered by the laws of England and Wales, Brazil, US, or Canada (federal, state or provincial). The information is intended to be confidential and may be legally privileged. If you are not the intended recipient, you are hereby notified that any retention, dissemination, distribution, interception or copying of this communication is strictly prohibited and may subject you to further legal action. Reply to the sender if you received this email by accident, and then delete the email and any attachments.

	[[alternative HTML version deleted]]

More information about the R-help mailing list