R:一起绘制箱线图和函数图

问题描述 投票:0回答:3

我想一起绘制函数和箱线图。但它效果不佳,部分原因可能是箱线图中的 x 轴不被视为连续变量。我想知道如何使用和不使用 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")
r ggplot2 boxplot
3个回答
2
投票

为了使您的

ggplot2
方法发挥作用,您可以使用
group
美学,而不是转换为
factor
:

library(ggplot2)

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


0
投票

这可能不是一个好的解决方案,但对于非 ggplot 情况,

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

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

0
投票

使用 Base R,您可以简单地运行

boxplot(y ~ x, dat)
points(as.factor(x), f(x), col = "red", type = "l")

© www.soinside.com 2019 - 2024. All rights reserved.