3

我有一个条形图,下半部分应该适合这个公式: . 现在我想绘制整个条形图并在条形图的最后一部分显示拟合模型,因为它仅适用于该部分。但是,我找不到仅在后半部分显示折线图的方法。如果我只是做类似的事情y~axexp(-b*x^2)


submitted=c(1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 3L, 2L, 1L, 1L, 4L, 
3L, 2L, 11L, 6L, 2L, 16L, 7L, 17L, 36L, 27L, 39L, 41L, 33L, 42L, 
66L, 92L, 138L, 189L, 249L, 665L, 224L, 309L, 247L, 641L, 777L, 
671L, 532L, 749L, 506L, 315L, 292L, 281L, 130L, 137L, 91L, 40L, 
27L, 34L, 19L, 1L)
x=seq(0:(length(submitted)-1))
y1=rs$submitted[30:(length(submitted)-1)]
x1=seq(0:(length(y1)-1))
fit1=nls(y1~a*x1*exp(-b*x1^2),start=list(a=500,b=.01),trace=TRUE)
barplot(submitted,names.arg=x, las=2, cex.axis=0.8, cex=0.8)
lines(predict(fit1))

该行已显示,但位置错误。那么如何控制画线的位置呢?

4

2 回答 2

3

一个可重现的示例会有所帮助,但问题可能是条形图不在您期望的 x 坐标处。您可以通过捕获函数的输出来找出条形的 x 坐标barplot

dat <- 1:5                   # fake data for barplot
fit <- dat+rnorm(5, sd=0.1)  # fake fitted values

bp <- barplot(dat)           # draw plot and capture x-coordinates
lines(bp, fit)               # add line

编辑:
相同的原理可用于添加部分行。稍微重写你的代码以获得一个索引idx,显示你想要建模的数据部分:

x <- 0:(length(submitted)-1) 
idx <- 30:(length(submitted)-1)  # the part of the data to be modeled
y1 <- submitted[idx] 
x1 <- idx-30 
fit1 <- nls(y1~a*x1*exp(-b*x1^2),start=list(a=500,b=.01),trace=TRUE) 
# capture the midpoints from the barplot
bp <- barplot(submitted,names.arg=x, las=2, cex.axis=0.8, cex=0.8) 
# subset the midpoints to the range of the fit
lines(bp[idx], predict(fit1)) 

(注意我也改成seq(0:n)0:n,因为第一个没有给你一个 0 到 n 的序列。)

于 2010-02-16T16:18:34.727 回答
0

从 Aniko 那里得到答案,并将其重塑为您的具体问题。我使用了submitted您发布的数据。

定义你的变量:

y1 <- submitted[30:(length(submitted)-1)]
x1 <- seq(length(y1))

以这种方式使用该seq()功能就足够了。它已经为您完成了这项工作。然后您进行拟合并捕获barplot()Aniko 提到的 x 值。这会将 x 值保存在矩阵中,因此我as.vector()之后使用它来将其转换为向量并使事情变得更容易一些。

fit1 <- nls(y1~a*x1*exp(-b*x1^2),start=list(a=500,b=.01),trace=TRUE)
bar <- barplot(submitted, las=2, cex.axis=0.8, cex=0.8)
bar2 <- as.vector(bar)

如果您简单地打印您bar2的值,您将看到确切的值,现在您可以指定在图中放置拟合的位置。确保在您的以下lines()函数中,x 向量与 y 向量的长度相同。例如,您可以简单地对该功能进行一些额外的检查length()。这是您放置在条形图后半部分的适合度:

lines(x = bar2[30:(length(bar2)-1)], y = predict(fit1))
于 2010-02-16T16:12:44.730 回答