Search code examples
rggplot2boxplot

R: plot boxplot and a function plot together


I want to plot a function and boxplot together. But it is not working well partly because x-axis in boxplot is not regarded as a continuous variable, perhaps. I want to know how to do it with and without ggplot2.

f <- function (x) x*(1-exp(-(24)/(1+0.2*x)))
x <- rep(seq(0,100,by=10),each=100)
y <- rnorm(length(x),f(x),1)

library(ggplot2)
dat <- data.frame(x=x,y=y)
ggplot(dat,aes(x=factor(x),y=y))+geom_boxplot()+geom_function(fun=f,color="red")

boxplot(dat$y~dat$x)
xx <- seq(0,100,length=100)
points(xx,f(xx),col="red",type="l")

Solution

  • To make your ggplot2 approach work you could use the group aesthetic instead of converting to a factor:

    library(ggplot2)
    
    ggplot(dat, aes(x = x, y = y)) +
      geom_boxplot(aes(group = x)) +
      geom_function(fun = f, color = "red")