Search code examples
rplotpredictionnonlinear-functionsnonlinear-optimization

How to draw my function to plot with data in R


I have data about response time at web site according users that hit at the same time.

For example:
10 users hit the same time have (average) response time 300ms
20 users -> 450ms etc

I import the data in R and I make the plot from 2 columns data (users, response time). Also I use the function loess to draw a line about those points, at the plot.

Here's the code that I have wrote:

users <- seq(5,250, by=5)
responseTime <- c(179.5,234.0,258.5,382.5,486.0,679.0,594.0,703.5,998.0,758.0,797.0,812.0,804.5,890.5,1148.5,1182.5,1298.0,1422.0,1413.5,1209.5,1488.0,1632.0,1715.0,1632.5,2046.5,1860.5,2910.0,2836.0,2851.5,3781.0,2725.0,3036.0,2862.0,3266.0,3175.0,3599.0,3563.0,3375.0,3110.0,2958.0,3407.0,3035.5,3040.0,3378.0,3493.0,3455.5,3268.0,3635.0,3453.0,3851.5)

data1 <- data.frame(users,responseTime)
data1

plot(data1, xlab="Users", ylab="Response Time (ms)")
lines(data1)

loess_fit <- loess(responseTime ~ users, data1)
lines(data1$users, predict(loess_fit), col = "green")

Here's my plot's image:

enter image description here

My questions are:

  1. How to draw my nonlinear function at the same plot to compare it with the other lines?
    example: response_time (f(x)) = 30*users^2.

  2. Also how to make predictions for the line of function loess and for my function and show them to the plot, example: if I have data until 250 users, make prediction until 500 users


Solution

  • If you know the equation of the line that you want to draw, then just define a variable for your prediction:

    predictedResponseTime <- 30 * users ^ 2
    lines(users, predictedResponseTime)
    

    If the problem is that you want to fit a line, then you need to call a modelling function.

    Since loess is a non-parametric model, is isn't appropriate to use it to make predictions outside of the range of your data.

    In this case, a simple (ordinary least squares) linear regression using lm provides a reasonable fit.

    model <- lm(responseTime ~ users)
    
    prediction <- data.frame(users = 1:500)
    prediction$responseTime <- predict(model, prediction)
    with(prediction, lines(users, responseTime))