R 条形图最后一部分的绘图线

R 条形图最后一部分的绘图线,r,model,bar-chart,R,Model,Bar Chart,我有一个柱状图,其下半部分应符合以下公式: 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,

我有一个柱状图,其下半部分应符合以下公式:
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))

显示该行,但位置错误。那么,我如何才能控制线的绘制位置呢?

从Aniko那里得到答案,并根据您的具体问题对其进行重塑。我使用了您发布的数据
提交的

定义变量:

y1 <- submitted[30:(length(submitted)-1)]
x1 <- seq(length(y1))
如果您只需打印
bar2
,您将看到准确的值,现在您可以指定在绘图中放置拟合的位置。确保在下面的
lines()
函数中,x向量的长度与y向量的长度相同。例如,您可以简单地使用
length()
函数执行一些附加检查。 以下是放置在柱状图后半部分的适合度:

lines(x = bar2[30:(length(bar2)-1)], y = predict(fit1))

一个可复制的示例可能会有所帮助,但问题可能在于条形图未位于您期望的x坐标处。通过捕获
barplot
功能的输出,可以找到条形图的x坐标:

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

(请注意,我还将
seq(0:n)
更改为
0:n
,因为第一个没有给您0到n的序列)。

我在我的原始帖子中添加了一些示例数据。正如你所能做的那样,它不同于你伪造的数据。我希望有帮助。
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
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))