Plot side-by-side Impulse Response in R package "vars" - r

library(vars)
data(Canada)
var_fit <- VAR(Canada, p = 1)
var_irf <- irf(var_fit, impulse = c("U", "rw"), response = "prod")
How do I plot the two Impulse Responses in a figure side-by-side
Normally, I'd use par(mfrow = c(1,2)), but it doesn't work as expected. Any help?

I found the same problem. I solved "manually", here a example for a model VAR(1) with two variables.
impulse<-irf(model)
irf1<-data.frame(impulse$irf$y1[,1],impulse$Lower$y1[,1],
impulse$Upper$y1[,1])
irf2<-data.frame(impulse$irf$y1[,2],impulse$Lower$y1[,2],
impulse$Upper$y1[,2])
par(mfrow=c(1,2), bg="azure2")
matplot(irf1, type="l", lwd=2, col="blue2",
ylab=expression(y[1]), lty=c(1,2,2))
matplot(irf2, type="l", lwd=2, col="red2",
ylab=expression(y[1]), lty=c(1,2,2))

Related

R: Plot lines are very thick

When using matplot to plot a matrix using:
matplot(t, X[,1:4], col=1:4, lty = 1, xlab="Time", ylab="Stock Value")
my graph comes out as:
How do I reduce the line thickness? I previously used a different method and my graph was fine:
I have tried manupilating lwd but to no avail.
Even tried plot(t, X[1:4097,1]), yet the line being printed is very thick. Something wrong with my R?
EDIT: Here is the code I used to produce the matrix X:
####Inputs mean return, volatility, time period and time step
mu=0.25; sigma=2; T=1; n=2^(12); X0=5;
#############Generating trajectories for stocks
##NOTE: Seed is fixed. Changing seed will produce
##different trajectories
dt=T/n
t=seq(0,T,by=dt)
set.seed(201)
X <- matrix(nrow = n+1, ncol = 4)
for(i in 1:4){
X[,i] <- c(X0,mu*dt+sigma*sqrt(dt)*rnorm(n,mean=0,sd=1))
X[,i] <- cumsum(X[,i])
}
colnames(X) <- paste0("Stock", seq_len(ncol(X)))
Just needed to add type = "l" to matplot(....). Plots fine now.
matplot(t, X[,1:4], col=1:4, type = "l", xlab="Time", ylab="Stock Value")

Plotting several variables on the same scale in R

I've tried over and over to solve this issue but I can't get it down. I have estimated a Beta-t-EGARCH model and a GARCH-t model in R and now I need to plot the results over the same plot. The final result is horrible, since the variables don't share the same scale on the y axis. I'm new to R, so please don't blame me :).
Here's the code:
library(quantmod)
library(betategarch)
library(fGarch)
library(ggplot2)
getSymbols("GOOG",src="yahoo")
google_ret <- abs(periodReturn(GOOG, period="daily", subset=NULL, type="log"))-mean(abs(periodReturn(GOOG, period="daily", subset=NULL, type="log")))
googcomp <- tegarch(google_ret, asym=FALSE, skew=FALSE)
goog1stdev <- fitted(googcomp)
#now we try to fit a standard GARCH-t model
googgarch <- garchFit(data=google_ret, cond.dist="sstd")
googgarch2 <- garchFit(data=google_ret, cond.dist="sstd", include.mean = FALSE, include.delta = FALSE, include.skew = FALSE, include.shape = FALSE, leverage = FALSE, trace = TRUE)
volatility <- volatility(googgarch2, type = "sigma")
plot(google_ret)
par(new=TRUE)
plot(googgarch2, which=2)
par(new=TRUE)
plot(goog1stdev, col="red")
The final result is a plot completely out of scale on the y axis, with variables that have lower values plotted above higher ones. Thanks a lot to anybody that wants to help me!
The recommended approach is to plot them as different plots stacked on top of each other:
layout(matrix(1:3,3))
plot(google_ret)
plot(googgarch2, which=2)
plot(goog1stdev, col="red")
You can get rid of the whitespace with calls to par("mar") to adjust margin sizes:
opar=par(mar=par("mar") -c(1,0,3,0)) # opar will then let your restore previous values
..... plotting efforts
par(opar)
I don't know your domain very much but if you cna use shifted y-ordinates then this produces a somewhat cleaned up version with overlayed plots:
png()
plot(google_ret, ylim=c(0,1), ylab="ylab="Google Returns(black); GGarch x10 +0.5 (blue); STD + 0.3(red)" )
par(new=TRUE)
plot(googgarch2#data +.5, type="l", col="blue",axes=FALSE, ylab="", main="",ylim=c(0, 1)) ;abline(h=.5, col="blue")
par(new=TRUE);
plot( 10*coredata(goog1stdev) + .3, col="red", type="l", axes=FALSE, main="",ylim=c(0,1), ylab=""); abline(h=.3, col="red")
dev.off()

Doing PCA with varimax rotation in R

My code has gone south.
I'm importing a data 578x17 sheet from csv using the:
Data=read.csv("Data.csv", header=TRUE, sep=',', dec='.', row.names= 1 , stringsAsFactors=TRUE)
My correlations and covariance matrices are the same.
When I try to do a PCA and a PCA with a Varimax Rotation, I get the same results:
PCA=princomp(x = Data, cor = TRUE, scores = TRUE)
Varimax<-princomp(Data, rotation="varimax")
When I try to do a Varimax rotation in a different way, I get:
varimax<-varimax(PCA$rotation[,1:5])
Error in if (nc < 2) return(x) : argument is of length zero
I'm not sure whether the problem is my code, or my .csv file, but any help would be greatly appreciated!
varimax rotation in PCA with vegan's rda()
The basics of this answer has been taken from:
https://stats.stackexchange.com/questions/59213/how-to-compute-varimax-rotated-principal-components-in-r
suppose that the data matrix name is mydata
library(vegan)
library(pracma)
pca.env = rda(mydata, scale=T)
loading = scores(pca.env, choices=c(1,2))$species #choices determines which pc to be taken
rloading = varimax(loading)$loadings
iloading = t(pinv(rloading))
scores = scale(mydata) %*% iloading
biplot
r = range(c(rloading, scores))
plot(scores, xlim = r, ylim= r, xlab= "PC1 ", ylab= "PC2 ")
arrows(0,0, rloading[,1], rloading[,2], length=0.1, col=2)
text(rloading[,1], rloading[,2], labels = colnames(mydata), pos=3, col=2)
text(scores[,1], scores[,2], labels = rownames(mydata), pos = 3)
abline(h=0, lty=3)
abline(v=0, lty=3)

Why isn't this plotting multiple functions in one graph?

I'm having some problems trying to plot multiple reliability functions in one single graph from a inverse gaussian distirbution. I need the functions to be lines, and all I got is points, when trying to set type="l", it happens to be a mess drawing mulitle lines everywhere.
Here is the code
library("statmod")
x<-rinvgauss(90,0.000471176,0.0000191925)
y<-rinvgauss(90,0.000732085,0.000002982015)
z<-rinvgauss(180,0.000286672,0.00000116771)
den<-pinvgauss(x,0.000471176,0.0000191925)
dens<-pinvgauss(y,0.000732085,0.000002982015)
densi<-pinvgauss(z,0.000286672,0.00000116771)
rel<-1-den
reli<-1-dens
relia<-1-densi
plot(x,rel, xlim=c(0,0.002), col="red")
points(y,reli, col="blue")
points(z,relia, col="black")
I would really appreciate any help on this!
The problem is your x, y, z values aren't sorted...
library("statmod")
x <- sort(rinvgauss(90,0.000471176,0.0000191925))
y <- sort(rinvgauss(90,0.000732085,0.000002982015))
z <- sort(rinvgauss(180,0.000286672,0.00000116771))
den <- pinvgauss(x,0.000471176,0.0000191925)
dens <- pinvgauss(y,0.000732085,0.000002982015)
densi <- pinvgauss(z,0.000286672,0.00000116771)
rel <- 1-den
reli <- 1-dens
relia <- 1-densi
plot(x,rel, xlim=c(0,0.002), col="red", type="l")
lines(y,reli, col="blue")
lines(z,relia, col="black")
Your values weren't sorted. This should work:
x<-sort(rinvgauss(90,0.000471176,0.0000191925))
y<-sort(rinvgauss(90,0.000732085,0.000002982015))
z<-sort(rinvgauss(180,0.000286672,0.00000116771))
den<-sort(pinvgauss(x,0.000471176,0.0000191925))
dens<-sort(pinvgauss(y,0.000732085,0.000002982015))
densi<-sort(pinvgauss(z,0.000286672,0.00000116771))
rel<-1-den
reli<-1-dens
relia<-1-densi
plot(x,rel, xlim=c(0,0.002), col="red",type="l")
lines(y,reli, col="blue")
lines(z,relia, col="black")

superpose a histogram and an xyplot

I'd like to superpose a histogram and an xyplot representing the cumulative distribution function using r's lattice package.
I've tried to accomplish this with custom panel functions, but can't seem to get it right--I'm getting hung up on one plot being univariate and one being bivariate I think.
Here's an example with the two plots I want stacked vertically:
set.seed(1)
x <- rnorm(100, 0, 1)
discrete.cdf <- function(x, decreasing=FALSE){
x <- x[order(x,decreasing=FALSE)]
result <- data.frame(rank=1:length(x),x=x)
result$cdf <- result$rank/nrow(result)
return(result)
}
my.df <- discrete.cdf(x)
chart.hist <- histogram(~x, data=my.df, xlab="")
chart.cdf <- xyplot(100*cdf~x, data=my.df, type="s",
ylab="Cumulative Percent of Total")
graphics.off()
trellis.device(width = 6, height = 8)
print(chart.hist, split = c(1,1,1,2), more = TRUE)
print(chart.cdf, split = c(1,2,1,2))
I'd like these superposed in the same frame, rather than stacked.
The following code doesn't work, nor do any of the simple variations of it that I have tried:
xyplot(cdf~x,data=cdf,
panel=function(...){
panel.xyplot(...)
panel.histogram(~x)
})
You were on the right track with your custom panel function. The trick is passing the correct arguments to the panel.- functions. For panel.histogram, this means not passing a formula and supplying an appropriate value to the breaks argument:
EDIT Proper percent values on y-axis and type of plots
xyplot(100*cdf~x,data=my.df,
panel=function(...){
panel.histogram(..., breaks = do.breaks(range(x), nint = 8),
type = "percent")
panel.xyplot(..., type = "s")
})
This answer is just a placeholder until a better answer comes.
The hist() function from the graphics package has an option called add. The following does what you want in the "classical" way:
plot( my.df$x, my.df$cdf * 100, type= "l" )
hist( my.df$x, add= T )

Resources