Plotting a piecewise function in R - r

I was reading other similar questions in this site about how to plot a piecewise function in R and I write this code
myfunction = function(x){(x<-1)*(x^2+2*x)+(-1<=x & x<=1)*x+(x>1)*(-1)}
g=Vectorize(myfunction)
plot(g,-5,5)
However the plot is just a straight line, that is, it doesnt plot the defined function. What Im doing wrong?

<- is assignment and won't be interpreted as "less than negative". Add a space in there and you'll see what you expect.
myfunction = function(x){(x< -1)*(x^2+2*x)+(-1<=x & x<=1)*x+(x>1)*(-1)}

Related

Empirical Cumulative Density Function - R software

I have a problem with plotting ECDF. I try to reverse the x axis value like 1-(the function).
Because I wanna have smaller in the beginning of the graph and decreasing like in my reference graph.
load("91-20.RData")
ts <- data.frame(dat91,dat92,dat93,dat94,dat95,dat96,dat97,
dat98,dat99,dat00,dat11,dat12,dat12,dat13,
dat14,dat15,dat16,dat17,dat18,dat19,dat20)
ts
tsclean <- na.omit(ts)
#--------------------------------------------------------
ggplot(tsclean, aes(tsclean$dat91)) +
stat_ecdf(geom = "step")
This graph what i have, but i wanna duplicate like the reference
load("91-20.RData")
ts <- data.frame(dat91,dat92,dat93,dat94,dat95,dat96,dat97,
dat98,dat99,dat00,dat11,dat12,dat12,dat13,
dat14,dat15,dat16,dat17,dat18,dat19,dat20)
ts
tsclean <- na.omit(ts)
I think the graph you're looking for is called an "exceedance" graph. A web search finds some resources; try a web search for "R exceedance graph".
EDIT: This is more suitable as a comment than an answer, but my web browser is being unhelpful at the moment; sorry for the distraction.

Trouble getting started on my user defined function in R that creates 3 plots.

I am new to R. I've been trying to work on my code but I am having trouble understanding which 'parts' go where. This is the code I was given:
df=10
boxplot(rt(1000,df),rnorm(1000),names=c(paste("t,df=",df),"Standard Normal"))
x=seq(0,1,length=150)
plot(qt(x,df),qnorm(x),xlab=paste("t, df=",df),ylab="standard
Normal",main="qq-plot")
abline(0,1)
curve(dnorm(x),-3.5,3.5,main="Density Comparison")
curve(dt(x,df),lty=2,add=TRUE)
legend("topright",legend=c("standard
normal",paste("t,df=",df)),lty=c(1,2))
I am supposed to create a user defined function that takes df as the input and output 3 types of plots. I need to use: df=5,10,25, and 50.
This is what I have so far. Please dumb it down for me since I'm not very familiar with R terminology and I am not sure I am placing things where they are supposed to go..:
my.plot = function(n, df) {
a = rt(n,df)
b=rnorm(1000)
x= seq(0,1,length=150)
qt=qt(x,df)
qn=qnorm(x)
dn=dnorm(x)
ledt=dt(x,df)
n=1000
}
thebox= boxplot(a,b,names=c(paste("t,df=",df),"Stand rd Normal")) #1boxplot.
theplot= plot(qt,qn,xlab=paste("t, df=",df),ylab="standard Normal",main="qq-plot")
abline(0,1)
onecurve= curve(dn,-3.5,3.5,main="Density Comparison") #density curve
twocurve= curve(ledt, lty=2,add=TRUE)
legend("topright",legend=c("standard normal",paste("t,df=",df)),lty=c(1,2)
}
return(thebox)
return(theplot)
return(oneplot)
return(twocurve)
}
par(mfrow=c(1,3))
my.plot(1000,5)
my.plot(1000,10)
my.plot(1000,25)
my.plot(1000,50)
It works like this:
1. Your only input parameter is df. So your function will have only one input variable.
2. Since you already have the remaining code functional (i.e. after defining df) that code can be used as it is.
Below is a simple implementation from your demo code. You can modify it to suite your needs.
my.plot <- function(df) {
par(mfrow=c(1,3))
boxplot(rt(1000,df),rnorm(1000),names=c(paste("t,df=",df),"Standard Normal"))
x=seq(0,1,length=150)
plot(qt(x,df),qnorm(x),xlab=paste("t, df=",df),ylab="standard
Normal",main="qq-plot")
abline(0,1)
curve(dnorm(x),-3.5,3.5,main="Density Comparison")
curve(dt(x,df),lty=2,add=TRUE)
legend("topright",legend=c("standard
normal",paste("t,df=",df)),lty=c(1,2))
par(mfrow=c(1,1))
}
my.plot(5)
for(df in c(5,10,15,25)) my.plot(df)

R, graph of binomial distribution

I have to write own function to draw the density function of binomial distribution and hence draw
appropriate graph when n = 20 and p = 0.1,0.2,...,0.9. Also i need to comments on the graphs.
I tried this ;
graph <- function(n,p){
x <- dbinom(0:n,size=n,prob=p)
return(barplot(x,names.arg=0:n))
}
graph(20,0.1)
graph(20,0.2)
graph(20,0.3)
graph(20,0.4)
graph(20,0.5)
graph(20,0.6)
graph(20,0.7)
graph(20,0.8)
graph(20,0.9)
#OR
graph(20,scan())
My first question : is there any way so that i don't need to write down the line graph(20,p) several times except using scan()?
My second question :
I want to see the graph in one device or want to hit ENTER to see the next graph. I wrote
par(mfcol=c(2,5))
graph(20,0.1)
graph(20,0.2)
graph(20,0.3)
graph(20,0.4)
graph(20,0.5)
graph(20,0.6)
graph(20,0.7)
graph(20,0.8)
graph(20,0.9)
but the graph is too tiny. How can i present the graphs nicely with giving head line n=20 and p=the value which i used to draw the graph?[though it can be done by writing mtext() after calling the function graphbut doing so i have to write a similar line few times. So i want to do this including in function graph. ]
My last question :
About comment. The graphs are showing that as the probability of success ,p is increasing the graph is tending to right, that is , the graph is right skewed.
Is there any way to comment on the graph using program?
Here a job of mapply since you loop over 2 variables.
graph <- function(n,p){
x <- dbinom(0:n,size=n,prob=p)
barplot(x,names.arg=0:n,
main=sprintf(paste('bin. dist. ',n,p,sep=':')))
}
par(mfcol=c(2,5))
mapply(graph,20,seq(0.1,1,0.1))
Plotting base graphics is one of the times you often want to use a for loop. The reason is because most of the plotting functions return an object invisibly, but you're not interested in these; all you want is the side-effect of plotting. A loop ignores the returned obects, whereas the *apply family will waste effort collecting and returning them.
par(mfrow=c(2, 5))
for(p in seq(0.1, 1, len=10))
{
x <- dbinom(0:20, size=20, p=p)
barplot(x, names.arg=0:20, space=0)
}

qplot dynamic plotting

I would like to create dynamic plotting over given dates, ie i want the plots appear one after another through specific dates when the code is run. This code seems to work with plot function but not with qplot.
any ideas?
thanks in advance,
x with headings t, date, AUM, profit
windows(5,5)
dev.set()
for (i in 1:10){
z <- x[x$t == i,]
a <- unique(z$date)
qplot(z$AUM,z$profit,main=a,xlim=range(0:2.5e+08),ylim=range(0:6e+06))
}
You need to add a print() call, i.e. print(qplot(...)).
The reason is that ggplot2 uses grid graphics which requires a print call.
print(qplot(z$AUM,z$profit,main=a,xlim=range(0:2.5e+08),ylim=range(0:6e+06)))
This is R FAQ 7.16.

Multiple plots with high-level plotting functions, especially plot.rqs()

I am trying to plot two regression summaries side-by-side with one centered title. Each regression summary is generated by plot.rqs() and amounts to a set of 9 plots.
I've tried using par(mfrow=c(1,2)) already, but as I learnt from Paul Murrel's (2006) book, high-level functions like plot.rqs() or pairs() save the graphics state before drawing and then restore the graphics state once completed, so that pre-emptive calls to par() or layout() can't help me. plot.rqs() doesn't have a 'panel' function either.
It seems that the only way to achieve the result is to modify the plot.rqs() function to get a new function, say modified.plot.rqs(), and then run
par(mfrow=c(1,2))
modified.plot.rqs(summary(fit1))
modified.plot.rqs(summary(fit2))
par(mfrow=c(1,1))
From there I might be able to work out how to add an overall title to the image using layout(). Does anyone know how to create a modified.plot.rqs() function that could be used in this way?
Thanks
You can patch a function as follows:
use dput and capture.output to retrieve
the code of the function, as a string;
change it as you want (here, I just replace each occurrence of par
with a function that does nothing);
finally evaluate the result to produce a new function.
library(quantreg)
a <- capture.output(dput(plot.summary.rqs))
b <- gsub("^\\s*par\\(", "nop(", a)
nop <- function(...) {}
my.plot.summary.rqs <- eval(parse(text=b))
First we generate an example object, fm . Then we copy plot.rqs and use trace on the copy to insert par <- list at top effectively nullifying any use of par within the function. Then we do the same with plot.summary.rqs. Finally we test it out with our own par:
library(quantreg)
example(plot.rqs) # fm to use in example
# plot.rqs
plot.rqs <- quantreg::plot.rqs
trace("plot.rqs", quote(par <- list), print = FALSE)
# plot.summary.rqs
plot.summary.rqs <- quantreg::plot.summary.rqs
trace("plot.summary.rqs", quote(par <- list), print = FALSE)
# test it out
op <- par(mfrow = c(2, 2))
plot(summary(fm))
plot(fm)
title("My Plots", outer = TRUE, line = -1)
par(op)
EDIT: added plot.summary.rqs.

Resources