Poisson regression line - r

How can I add a poisson regression line to a plot? I tried the following, but the abline function doesn't not work. This is because abline() uses the intercept and slope, whereas a poisson regression line uses a log-link.
x = rpois(12, 5)
plot(x, axes = F)
axis(1,at=1:length(month.name), labels = month.name)
axis(side = 2)
y = c(1:12)
poislm = glm(x~y, family=poisson)
abline(poislm)

How about from R-help
predProbs<-predict(poislm,data.frame(y=seq(min(y), max(y), length.out=100)), type="response")
lines(seq(min(y), max(y), length.out=100), predProbs, col=2, lwd=2)

Related

How can I plot the regression lines analysis in R

I want to plot regression lines in R for technical analysis.
First, I regress the price on the date and I get the main regression line. However, also, I need lines that correspond to (Main regression line +- 2*standard deviation).
Do you know how I can implement this? I already checked the TTR package, but I couldn't find a built-in indicator for this purpose.
Thank you.
To obtain points on the regression line, you can use the function predict on the fitted model. For confidence intervals, use the options interval and level, e.g.:
lsq <- lm(y ~ x, data)
predict(lsq, data.frame(x=c(12,45), interval="confidence", level=0.95)
To expand on #cdalitz answer this is how you plot the regression line with the confidence interval:
# Generate data
set.seed(123)
n = 100
x = runif(n)
y = 2 * x + rnorm(n, sd = 0.5)
m = lm(y ~ x)
newx = seq(min(x), max(x), length.out = 100)
pred = predict(m, newdata = data.frame(x = newx), interval="confidence", level=0.95)
# Plot data
plot(x, y)
# Plot model
abline(m)
# Plot 95% confidence interval
lines(newx, pred[, 2], col = "red", lty = 2)
lines(newx, pred[, 3], col = "red", lty = 2)
This question also shows many ways to do the same thing.

Plot residuals in R [duplicate]

Given two variables, x and y, I run a dynlm regression on the variables and would like to plot the fitted model against one of the variables and the residual on the bottom showing how the actual data line differs from the predicting line. I've seen it done before and I've done it before, but for the life of me I can't remember how to do it or find anything that explains it.
This gets me into the ballpark where I have a model and two variables, but I can't get the type of graph I want.
library(dynlm)
x <- rnorm(100)
y <- rnorm(100)
model <- dynlm(x ~ y)
plot(x, type="l", col="red")
lines(y, type="l", col="blue")
I want to generate a graph that looks like this where you see the model and the real data overlaying each other and the residual plotted as a separate graph on the bottom showing how the real data and the model deviate.
This should do the trick:
library(dynlm)
set.seed(771104)
x <- 5 + seq(1, 10, len=100) + rnorm(100)
y <- x + rnorm(100)
model <- dynlm(x ~ y)
par(oma=c(1,1,1,2))
plotModel(x, model) # works with models which accept 'predict' and 'residuals'
and this is the code for plotModel,
plotModel = function(x, model) {
ymodel1 = range(x, fitted(model), na.rm=TRUE)
ymodel2 = c(2*ymodel1[1]-ymodel1[2], ymodel1[2])
yres1 = range(residuals(model), na.rm=TRUE)
yres2 = c(yres1[1], 2*yres1[2]-yres1[1])
plot(x, type="l", col="red", lwd=2, ylim=ymodel2, axes=FALSE,
ylab="", xlab="")
axis(1)
mtext("residuals", 1, adj=0.5, line=2.5)
axis(2, at=pretty(ymodel1))
mtext("observed/modeled", 2, adj=0.75, line=2.5)
lines(fitted(model), col="green", lwd=2)
par(new=TRUE)
plot(residuals(model), col="blue", type="l", ylim=yres2, axes=FALSE,
ylab="", xlab="")
axis(4, at=pretty(yres1))
mtext("residuals", 4, adj=0.25, line=2.5)
abline(h=quantile(residuals(model), probs=c(0.1,0.9)), lty=2, col="gray")
abline(h=0)
box()
}
what you're looking for is resid(model). Try this:
library(dynlm)
x <- 10+rnorm(100)
y <- 10+rnorm(100)
model <- dynlm(x ~ y)
plot(x, type="l", col="red", ylim=c(min(c(x,y,resid(model))), max(c(x,y,resid(model)))))
lines(y, type="l", col="green")
lines(resid(model), type="l", col="blue")

how to calculate the slope of a smoothed curve in R

I have the following data:
I plotted the points of that data and then smoothed it on the plot using the following code :
scatter.smooth(x=1:length(Ticker$ROIC[!is.na(Ticker$ROIC)]),
y=Ticker$ROIC[!is.na(Ticker$ROIC)],col = "#AAAAAA",
ylab = "ROIC Values", xlab = "Quarters since Feb 29th 2012 till Dec 31st 2016")
Now I want to find the Point-wise slope of this smoothed curve. Also fit a trend line to the smoothed graph. How can I do that?
There are some interesting R packages that implement nonparametric derivative estimation. The short review of Newell and Einbeck can be helpful: http://maths.dur.ac.uk/~dma0je/Papers/newell_einbeck_iwsm07.pdf
Here we consider an example based on the pspline package (smoothing splines with penalties on order m derivatives):
The data generating process is a negative logistic models with an additive noise (hence y values are all negative like the ROIC variable of #ForeverLearner) :
set.seed(1234)
x <- sort(runif(200, min=-5, max=5))
y = -1/(1+exp(-x))-1+0.1*rnorm(200)
We start plotting the nonparametric estimation of the curve (the black line is the true curve and the red one the estimated curve):
library(pspline)
pspl <- smooth.Pspline(x, y, df=5, method=3)
f0 <- predict(pspl, x, nderiv=0)
Then, we estimate the first derivative of the curve:
f1 <- predict(pspl, x, nderiv=1)
curve(-exp(-x)/(1+exp(-x))^2,-5,5, lwd=2, ylim=c(-.3,0))
lines(x, f1, lwd=3, lty=2, col="red")
And here the second derivative:
f2 <- predict(pspl, x, nderiv=2)
curve((exp(-x))/(1+exp(-x))^2-2*exp(-2*x)/(1+exp(-x))^3, -5, 5,
lwd=2, ylim=c(-.15,.15), ylab=)
lines(x, f2, lwd=3, lty=2, col="red")
#DATA
set.seed(42)
x = rnorm(20)
y = rnorm(20)
#Plot the points
plot(x, y, type = "p")
#Obtain points for the smooth curve
temp = loess.smooth(x, y, evaluation = 50) #Use higher evaluation for more points
#Plot smooth curve
lines(temp$x, temp$y, lwd = 2)
#Obtain slope of the smooth curve
slopes = diff(temp$y)/diff(temp$x)
#Add a trend line
abline(lm(y~x))

reversing the cutoff values in R using ROCR packge

I am using a confusion matrix to create a ROC Curve. The problem I have is the cutoff values are revered. How to do I put them in ascending order?
pred <- prediction(predictions =c(rep(5,19),rep(7,24),rep(9,40),rep(10,42)), labels =
c(rep(0,18),rep(1,1),rep(0,7),rep(1,17),rep(0,4),rep(1,36),rep(0,3),rep(1,39)))
perf <- performance(pred,"tpr","fpr")
plot(perf,colorize=TRUE)
abline(0,1,col='red')
x = c(0.09375,0.21875,0.43750)
y = c(0.4193548,0.8064516,0.9892473)
points(x , y , col="red", pch=19)
text(x , y+0.03, labels= c("9","7","5"), col="red", pch=19)
predictions = c(rep(5,19),rep(7,24),rep(9,40),rep(10,42))
labels = c(rep(0,18),rep(1,1),rep(0,7),rep(1,17),rep(0,4),rep(1,36),rep(0,3),rep(1,39))
auc(predictions,labels)

Extract coefficient numeric for r plot legend

I'm trying to get the legend in a simple R plot to report the coefficient (i.e. slope) without manually extracting the value. Does anybody know how to code the legend so that it displays the value rather than the command? Thanks
y <- rnorm(100)
x <- sample(rnorm(100), 100, replace = TRUE)
plot(x, y)
mod <- lm(y ~x)
abline(lm(y~x))
legend("topleft", "Slope = coef(mod)[2]", col = "black", pch = 15, cex = .8)
paste0("Slope = ", coef(mod)[2])

Resources