【问题标题】:In R draw two lines, with slopes double and half the value of the best fit line在R中画两条线,斜率是最佳拟合线的两倍和一半
【发布时间】:2010-06-10 17:53:09
【问题描述】:

我有一个最佳拟合线绘制的数据。我需要画另外两条线。一个需要有两倍的斜率,另一个需要有一半的斜率。稍后我将使用该区域对它外部的点进行不同的着色,如下所示: Conditionally colour data points outside of confidence bands in R

示例数据集:

## Dataset from http://www.apsnet.org/education/advancedplantpath/topics/RModules/doc1/04_Linear_regression.html

## Disease severity as a function of temperature

# Response variable, disease severity
diseasesev<-c(1.9,3.1,3.3,4.8,5.3,6.1,6.4,7.6,9.8,12.4)

# Predictor variable, (Centigrade)
temperature<-c(2,1,5,5,20,20,23,10,30,25)

## For convenience, the data may be formatted into a dataframe
severity <- as.data.frame(cbind(diseasesev,temperature))

## Fit a linear model for the data and summarize the output from function lm()
severity.lm <- lm(diseasesev~temperature,data=severity)

# Take a look at the data
plot(
  diseasesev~temperature,
  data=severity,
  xlab="Temperature",
  ylab="% Disease Severity",
  pch=16,
  pty="s",
  xlim=c(0,30),
  ylim=c(0,30)
)
title(main="Graph of % Disease Severity vs Temperature")
par(new=TRUE) # don't start a new plot
abline(severity.lm, col="blue")

【问题讨论】:

  • 你确定这是你真正想做的吗?你意识到 bound 基本上是没有意义的,对吧?

标签: r plot linear-regression


【解决方案1】:

你可以使用

# This gets the coefficients of the linear regression (intercept and slope)
c <- coef(severity.lm)
abline(c[1], c[2]*2, col="red")
abline(c[1], c[2]/2, col="red")

【讨论】:

    【解决方案2】:
    diseasesev<-c(1.9,3.1,3.3,4.8,5.3,6.1,6.4,7.6,9.8,12.4)
    
    # Predictor variable, (Centigrade)
    temperature<-c(2,1,5,5,20,20,23,10,30,25)
    
    ## For convenience, the data may be formatted into a dataframe
    severity <- as.data.frame(cbind(diseasesev,temperature))
    
    ## Fit a linear model for the data and summarize the output from function lm()
    severity.lm <- lm(diseasesev~temperature,data=severity)
    
    line1 <- severity.lm$coefficients * c(1,2)
    line2 <- severity.lm$coefficients * c(1,.5)
    
    df <- as.data.frame(severity.lm[[12]])
    df2 <- adply(df,1,function(x) cbind(line1[2]*x[[2]]+line1[1], line2[2]*x[[2]]+line2[1]))
    
    plot(
      df2[df2[,1] >= min(df2[,c(3,4)]) & df2[,1] <= max(df2[,c(3,4)]),c(2,1)],
      xlab="Temperature",
      ylab="% Disease Severity",
      pch=16,
      pty="s",
      xlim=c(0,30),
      ylim=c(0,30)
    )
    title(main="Graph of % Disease Severity vs Temperature")
    par(new=TRUE) # don't start a new plot
    abline(severity.lm, col="blue")
    abline(line1, col="cyan")
    abline(line2, col="cyan")
    points(df2[df2[,1] < min(df2[,c(3,4)]) | df2[,1] > max(df2[,c(3,4)]),c(2,1)], pch = 16, col = 'red')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-19
      • 2020-07-22
      • 1970-01-01
      • 2016-03-06
      • 1970-01-01
      • 2014-08-26
      • 1970-01-01
      • 2017-03-01
      相关资源
      最近更新 更多