1

I have data in the form:

Num Percent  
5   9.44  
4   19.7  
4   10.64  
4   10.81  
4   10.97  
4   11.35  
3   13.18  
3   24.54  
3   24.99  
3   12.95  
3   13.17  
3   24.29  
3   13.81  
3   13.93  
3   27.87  
3   13.26  
2   41.41  
2   34.19  
2   41.6  
2   19.31  
2   34.4  
2   38.72  
2   18.16  
2   36.28  
2   18.95  
2   18.49

I would like to plot the data such that, along with the plot of 'num'(x) and 'percent'(y), the mean at every point of the x axis (2,3,4,5) is added to the plot and a regression line based on the mean series is plotted.

joran
  • 169,992
  • 32
  • 429
  • 468
userOfLife
  • 11
  • 1
  • 1
  • 2

1 Answers1

1

Calling your data frame DF

MeansByNum <- tapply(DF$Percent, DF$Num, mean) #Create an array of means by Num
NewDF <- data.frame(cbind(Num = as.numeric(as.vector(names(MeansByNum))),
                          Percent = as.numeric(MeansByNum)))
plot(Percent~Num, DF)
points(NewDF$Num, NewDF$Percent, col="red")
abline(lm(Percent~Num, NewDF))
Señor O
  • 17,049
  • 2
  • 45
  • 47
  • Thanks so much! Is there a another function besides abline() that I can use? abline() draws a straight line, and I would like to draw a better fitted regression line and also possibly display the equation of the line on the chart. – userOfLife Oct 30 '12 at 20:45
  • `LM <- lm(Percent~as.vector(Num^n), DF)` will get you the model. `plot(function(x) coef(LM)[1]+coef(LM)[2]*x^n,MIN,MAX,add=TRUE)` will draw the line. `legend(legend=round(coef(LM), digits=3),x="topleft")` will display the coefficients, but not the formula. – Señor O Oct 30 '12 at 20:49
  • @user1786672 when you say 'a better fitted regression line' note that the line it fits in that code *is a regression line*. How would you make a better fitting regression line? Do you mean to ask for a curve? Or are you asking for a weighted line? – Glen_b Oct 31 '12 at 06:58