Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

geom_smooth or stat_function with geom_boxplot

Tags:

r

ggplot2

I cannot get ggplot2 to display a geom_smooth() or stat_function() with my boxplot.

I ultimately want to display a custom stat_function overtop of a boxplot.

library(ggplot2)
#joke dataset, similar looking ish to my own data
data=data.frame(date=as.Date(c("2011-02-01","2011-02-01","2011-02-01","2011-    02-01","2011-02-01",
                         "2011-02-10","2011-02-10","2011-02-10","2011-02-10","2011-02-10",
                         "2011-02-20","2011-02-20","2011-02-20","2011-02-20","2011-02-20",
                         "2011-02-28","2011-02-28","2011-02-28","2011-02-28","2011-02-28",
                         "2011-03-10","2011-03-10","2011-03-10","2011-03-10","2011-03-10"),format="%Y-%m-%d"),
            spore=c(0,1,0,1,0,
                    1,2,0,1,1,
                    8,5,6,12,7,
                    18,24,25,32,14,
                    27,26,36,31,22)
            )
#plots boxplot but not geom_smooth()
ggplot(data,aes(x=date,y=spore,group=date))+geom_boxplot()+geom_smooth()

#or maybe add a stat_function() so that I can have a logistic growth that way?
#this is a made up function, I have a real function for my own data
test <- function(x) {(40)/(1+exp((15/2)-(1/2)*x))}
ggplot(data,aes(x=date,y=spore,group=date))+stat_function(fun=test)

I think the fact that my x values are dates is screwing me up, but I don't have a good work around for this. I am really at the end of my rope, and I have no idea how to fix this.

like image 828
Robin Choudhury Avatar asked Sep 17 '26 22:09

Robin Choudhury


1 Answers

It's not the dates. It's the group aesthetic. For geom_boxplot having groups will make nice seperate boxplots, but for geom_smooth it will try to make a smooth for each group, i.e. one point per line, i.e. no lines. The fix is straight-forward:

ggplot(data,aes(x=date,y=spore)) + 
  geom_boxplot(aes(group=date)) + 
  geom_smooth()

enter image description here

like image 168
Axeman Avatar answered Sep 20 '26 14:09

Axeman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!