【问题标题】:plot line over last part of barplot条形图最后部分的绘图线
【发布时间】:2010-02-16 16:00:14
【问题描述】:

我有一个条形图,它的后半部分应该适合这个公式: y~a<em>x</em>exp(-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))

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

【问题讨论】:

    标签: r model bar-chart


    【解决方案1】:

    一个可重现的示例可能会有所帮助,但问题可能是条形图不在您期望的 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
    

    编辑:
    相同的原理可用于添加部分线。稍微重写你的代码以获得一个索引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的序列。)

    【讨论】:

    • 我在原始帖子中添加了一些示例数据。如您所知,它与您的虚假数据不同。我希望它有所帮助。
    【解决方案2】:

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

    定义你的变量:

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

    以这种方式使用seq() 函数就足够了。它已经为您完成了这项工作。然后您进行拟合并捕获 Aniko 提到的 barplot() 的 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))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-28
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 1970-01-01
      • 2022-11-10
      相关资源
      最近更新 更多