 Andrea - 2 years ago 86
R Question

# R - Plotting confidence interval - plotting wrong lines

I am an Beginner in R and I hope you could help me with my problem.
I'm plotting two regression lines and confidence intervals in one plot. On set belongs to a calibration set the other to a validation set.

The problem appears by plotting the confidence intervals.
I think my code is right. But the plots seem to look wrong because they're kind of duplicated.
Can you help with this? Could you check the code?Please let me know if you need more information.

Thanks a lot!

``````daten
value  value.1
1  11.026320 134.3143
2   9.639924 141.2350
3  10.536648 141.6315
4   6.592298 122.5119
5   8.076660 120.7184
6   9.932515 130.9272
7   7.643655 127.1847
8   8.878946 125.0633
9  13.533913 139.9746
10 13.348582 144.0469
11 14.276273 141.2087
12 14.187630 139.1795
13 13.857432 148.1722
14 13.253956 145.8228
15 14.354471 148.1940
16 14.248814 146.9241
17 17.686270 155.9812
18 17.705740 146.2779
19 17.391629 154.3003
20 17.491082 145.1513
21 18.336797 153.0822
22 19.360551 153.9610
23 18.365880 157.4013
24 17.371320 149.0933

daten2
value  value.1
1  11.027943 136.4339
2  10.725851 131.2016
3   5.494134 122.1194
4  10.987261 142.4861
5   6.090814 122.3194
6   9.983886 130.3030
7  11.010931 142.7053
8   6.641026 123.9638
9  13.198628 131.7118
10 14.061979 144.1937
11 13.822600 144.9910
12 14.153742 144.8122
13 14.195045 145.7297
14 14.465848 144.8645
15 12.811249 137.6729
16 13.194417 143.7291
17 21.151684 158.4400
18 21.405668 156.9390
19 18.006218 154.5199
20 17.235035 153.8093
21 20.934721 161.3653
22 19.560745 157.4780
23 17.401843 151.5338
24 20.081625 150.0368

plot(daten\$value.1, daten\$value, xlab="x", ylab="y", main="Regression", type="n")

model<-lm(value~value.1, data=daten)
model

abline(model, col="black")

model2<-lm(value~value.1, data=daten2)
par(new=TRUE)

abline(model2, col="black", lty=3)
model2

conf.int =  predict(model, interval="confidence",
level = 0.95)
conf.int

conf.lower=conf.int[,2]
conf.lower
conf.upper = conf.int[,3]

conf.int2 =  predict(model2, newdata=daten2,interval="confidence",
level = 0.95)
conf.int2

conf.lower2=conf.int2[,2]
conf.upper2 = conf.int2[,3]

lines(daten\$value.1, conf.lower,col="red")
lines(daten\$value.1, conf.upper,col="red")
lines(daten2\$value.1,conf.lower2, col="red", lty=3)
lines(daten2\$value.1,conf.upper2, col="red", lty=3)
`````` Oriol Mirosa
It's hard to know what the problem is without seeing the data or a graph so that we can see what you mean by 'kind of duplicated'. But if the problem is with the confidence interval lines, I suspect the issue might be with the ordering of the variables in the `lines` commands. Have you tried sorting both variables to make sure that the x and y in the lines correspond to each other, like this?
``````lines(sort(daten\$value.1), sort(conf.lower),col="red")