So I need to graph a confidence interval for a prediction I ran. I can run the prediction, but when I go to graph the prediction I get a line through all of my data points as opposed to getting the actual confidence interval.
GunRate <- seq(0,100, length = 51)
LinearPredictionA <- predict(ModelA,
interval = "confidence",
newdata = data.frame(ProportionAdultsLivingWithGun = GunRate,
LogMedianIncome = FinalSet$LogMedianIncome,
PctofPeopleinMetro = FinalSet$PctofPeopleinMetro,
PovertyRate = FinalSet$PovertyRate))
##This is my prediction model
plot(x = FinalSet$ProportionAdultsLivingWithGun,
y = FinalSet$ViolentCrime1K,
col = "red",
xlim = c(0, 80), ylim = c(0, 15),
xlab ="Proportion of Adults Living With a Gun",
ylab = "Violent Crime Rate per 1000",
main = "Violent Crime vs. Gun Ownership",
sub = "All 50 States & D.C.")
## This plot shows the actual data we used to obtain the prediction
lines(GunRate, LinearPredictionA[, "fit"], type = "l")
lines(GunRate, LinearPredictionA[, "lwr"], lty = "dashed", col = "green")
lines(GunRate, LinearPredictionA[, "upr"], lty = "dashed", col = "green")
These line functions are supposed to graph my CI, but instead I get the following graph
Here's an example of what's going wrong, using the built-in
mtcars
data frame:Now let's get predictions of
mpg
vs.wt
, but with 2 different alternating values ofhp
and 3 different alternating values ofcyl
:Note how the prediction jumps around, because
hp
andcyl
change for each successive value ofwt
:But when we keep
hp
andcyl
fixed, we get a straight line prediction formpg
vs.wt
:Instead of a single line, you can also plot predicted mpg vs. wt lines for several values of another variable. Below is an example where we plot a line for each value of
cyl
that we used to createpredData
. This is easier withggplot2
so I've used that package. Using lines for the confidence intervals would make the plot difficult to understand, so I've shown the CI with a fill instead: