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

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")

Related

How to create a monomial plot in R?

I want to create a function, that result will be a plot of moniomals ( degree less than "n").
I wrote the simple code.
Monomial=function(m){
x=1:100
y=1:100
for(i in m) x2=x^m
plot(y,x2,type="l",col="red",xlab="Arguments",ylab="Values",
main=expression("Monomials"))
But for example: Monomial(3) I getting plot x^3. I need yet x^1 and x^2. How to name each line?
Here is what you need:
Monomial <- function(m){
x <- 1:100
cols <- palette(rainbow(m))
plot(x,x,type="l",col = cols[1],xlab="Arguments",ylab="Values",
main=expression("Monomials"))
for (d in 2:m){
lines(x, x^d, type="l", col=cols[d])
}
legend(90, 60, legend=c(as.character(paste0("x",1:m))),
col=cols, lty=1, cex=0.6)
}
You need to generate colors. This is what the cols variable achieves. lines adds a new curve to existing axes. Finally, ledend adds a legend to the plot.

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()

Fit a normal fit in histogram with a x-log scale

I hope some of you help me. I am dealing with a plottiing a normal fit in my histogram with x-log scale. I use log scale because a normal histogram with my data has a long tail. My codes are like this..
breaks<- c(0,0.01, 0.05, 0.1,0.2,0.5,1,2,5,10,20,50,100,200,300) #bins
major <- c(0.1,1,10,100)
H <- hist(log10(B),plot=B) #using data "B"
plot(H$mids,H$counts,type="n",
xaxt="n",
xlab="B",ylab="Counts",
main="Histogram of B",
bg="lightgrey"
)
abline(v=log10(breaks),col="lightgrey",lty=2)
abline(v=log10(major),col="lightgrey")
abline(h=pretty(H$counts),col="lightgrey")
plot(H,add=T,freq=T,col="blue")
#Position of ticks
at <- log10(breaks)
#Creation X axis
axis(1,at=at,labels=10^at)
curve(dnorm(x, mean=mean(B), sd=sd(B)), add=TRUE) # 1st try
lines(density(B)) # 2nd try
xfit<-seq(min(B),max(B),length=40) # 3rd try
yfit<-dnorm(xfit,mean=mean(B),sd=sd(B))
yfit<-yfit*diff(H$mids[1:2])*length(B)
lines(xfit, yfit, col="red", lwd=2)
But 1st, 2nd, 3rd tries did not work..Please let me know how to add a normal fit into my histogram. Thank you very much for your help.
Summy
I just changed your first try so that you get what you want:
B <- rlnorm(10000)
H <- hist(log10(B), freq = FALSE, col="blue", xaxt="n", xlab="B")
at <- H$mids
axis(1,at=at,labels=round(10^at,2))
curve(dnorm(x, mean=mean(log10(B)), sd=sd(log10(B))), add=TRUE)
Hope it helps,
alex

R arrowed labelling of data points on a plot

I am looking to label data points with indices -- to identify the index number easily by visual examination.
So for instance,
x<-ts.plot(rnorm(10,0,1)) # would like to visually identify the data point indices easily through arrow labelling
Of course, if there's a better way of achieving this, please suggest
You can use arrows function:
set.seed(1); ts.plot(x <-rnorm(10,0,1), ylim=c(-1.6,1.6)) # some random data
arrows(x0=1:length(x), y0=0, y1=x, code=2, col=2, length=.1) # adding arrows
text(x=1:10, y=x+.1, 0, labels=round(x,2), cex=0.65) # adding text
abline(h=0) # adding a horizontal line at y=0
Use my.symbols from package TeachingDemos to get arrows pointing to the locations you want:
require(TeachingDemos)
d <- rnorm(10,0,1)
plot(d, type="l", ylim=c(min(d)-1, max(d)+1))
my.symbols(x=1:10, y=d, ms.arrows, angle=pi/2, add=T, symb.plots=TRUE, adj=1.5)
You can use text() for this
n <- 10
d <- rnorm(n)
plot(d, type="l", ylim=c(min(d)-1, max(d)+1))
text(1:n, d+par("cxy")[2]/2,col=2) # Upside
text(1:n, d-par("cxy")[2]/2,col=3) # Downside
Here a lattice version, to see the analogous of some base function.
set.seed(1234)
dat = data.frame(x=1:10, y = rnorm(10,0,1))
xyplot(y~x,data=dat, type =c('l','p'),
panel = function(x,y,...){
panel.fill(col=rgb(1,1,0,0.5))
panel.xyplot(x,y,...)
panel.arrows(x, y0=0,x1=x, y1=y, code=2, col=2, length=.1)
panel.text(x,y,label=round(y,2),adj=1.2,cex=1.5)
panel.abline(a=0)
})

Is it possible to create a 3d contour plot without continuous data in R?

I want to create a contour of variable z with the x,y,z data. However, it seems like we need to provide the data in increasing order.
I tried to use some code but it gave me the error.
I tried the following code: Trial 1:
age2100 <- read.table("temp.csv",header=TRUE,sep=",")
x <- age2100$x
y <- age2100$y
z <- age2100$z
contour(x,y,z,add=TRUE,col="black")
I got the following error
Error in contour.default(x, y, z, add = TRUE, col = "black") : increasing 'x' and 'y' values expected
I then tried to use ggplot2 to create the contour. I used the following code:
library("ggplot2")
library("MASS")
library("rgdal")
library("gpclib")
library("maptools")
age2100 <- read.table("temp.csv",header=TRUE,sep=",")
v <- ggplot(age2100, aes(age2100$x, age2100$y,z=age2100$z))+geom_contour()
v
I got the following error:
Warning message:
Not possible to generate contour data
Please find the data on the following location https://www.dropbox.com/s/mg2bo4rcr6n3dks/temp.csv
Can anybody tell me how to create the contour data from the third variable (z) from the temp.csv ? I need to do these many times so I am trying to do on R instead of Arcgis.
Here is an example of how one interpolates using interp from the akimapackage:
age2100 <- read.table("temp.csv",header=TRUE,sep=",")
x <- age2100$x
y <- age2100$y
z <- age2100$z
require(akima)
fld <- interp(x,y,z)
par(mar=c(5,5,1,1))
filled.contour(fld)
Here is an alternate plot using the imagefunction (this allows some flexibility to adding lower level plotting functions (requires the image.scale function, found here):
source("image.scale.R") # http://menugget.blogspot.de/2011/08/adding-scale-to-image-plot.html
x11(width=5, height=6)
layout(matrix(c(1,2), nrow=1, ncol=2), widths=c(4,1), height=6, respect=TRUE)
layout.show(2)
par(mar=c(4,4,1,1))
image(fld)
contour(fld, add=TRUE)
points(age2100$x,age2100$y, pch=".", cex=2)
par(mar=c(4,0,1,4))
image.scale(fld$z, xlab="", ylab="", xaxt="n", yaxt="n", horiz=FALSE)
box()
axis(4)
mtext("text", side=4, line=2.5)

Resources