使用geom_boxplot的geom_smooth或stat_function

时间:2016-02-15 07:45:45

标签: r ggplot2

我无法让ggplot2在我的箱子图中显示geom_smooth()stat_function()

我最终希望显示一个自定义的stat_function顶部的箱形图。

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)

我认为我的x值是日期的事实让我感到困惑,但我没有做好这方面的工作。 我真的走到了尽头,我不知道如何解决这个问题。

1 个答案:

答案 0 :(得分:4)

这不是日期。这是团体美学。对于具有组的geom_boxplot,将制作漂亮的单独箱图,但对于geom_smooth,它将尝试为每个组平滑,即每行一个点,即没有线。修复是直截了当的:

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

enter image description here