R plotting multiple locfit models with confidence intervals - r

I'm attempting to plot two locfit models within one plot however I am unable to get the second locfit model to plot the confidence intervals. I've created two locfit models:
1_fit = locfit(Y~Time,data=data_1)
2_fit = locfit(Y~Time,data=data_2)
Each can be plotted on their own just fine with the confidence intervals using the following:
plot(1_fit,band="local",type = "l", xlab = "Time", ylab = "Y-Axis",ylim=c(0,22),
col = "red",lwd = 5,font=3,main="Local Poly Fit 1",cex.lab=1.5, cex.axis=1.5,
cex.main=1.5, cex.sub=1.5)
However, when I attempt to plot an additional locfit model to the plot using:
lines(2_fit,col="blue")
I can only add the locfit line but not the confidence intervals. I've attempted to do:
lines(2_fit,band="local",col="blue")
But I get this message and no confidence intervals:
Warning message:
In plot.xy(xy.coords(x, y), type = type, ...) :
"band" is not a graphical parameter
I've also looked into using lines.locfit, but had no luck as R just says that it can't find the function lines.locfit.
I have a work around to put both plots within the same window using:
par(mfrow=c(2,1))
But would like to avoid this as it would make the plots more comparable if they were within the same plot.

Answer was provided by Richard Telford in comments. The following code was able to accomplish what I needed:
plot(1_fit,band="local",type = "l", xlab = "Time", ylab = "Y-Axis",ylim=c(0,22), xlim=c(0,12), col = "red",lwd = 5,font=3,main="Local Poly Fit 1",cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)`
par(new = TRUE)
plot(2_fit,band="local",type = "l", xlab = "Time", ylab = "Y-Axis",ylim=c(0,22), xlim=c(0,12),col = "blue",lwd = 5,font=3,main="Local Poly Fit 1",cex.lab=1.5, cex.axis=1.5, cex.main=1.5, cex.sub=1.5)`
I needed to be sure that ylim and xlim were equal as well as main, ylab, and xlab. Also a side note from Richard, 1_fit is not a legal name, I used it here just as a placeholder name but seems good knowledge to pass on.

Related

How change the y-axis numbers to be horizontal on an NMDS plot created in vegan?

Can I change the y-axis numbers to be horizontal on an NMDS plot created in vegan?
library(vegan)
sp <- poop[,28:34]
bat <- poop[,4:7]
mds1 <- metaMDS(sp, k=3,try=200)
plot(mds1$points[,1], mds1$points[,2], pch = as.numeric(bat$species),
col= as.numeric(bat$species),
xlab = "NMDS1", ylab= "NMDS2")
In R, the direction of labels is controlled by graphical parameter las (see ?par). You can also give this parameter in plot call for the metaMDS result. As you see from ?par, las=1 will put all labels horizontal.
More seriously, you should not plot metaMDS results like you do. It is better to use the dedicated plot method for the result, or if you want to do it all by yourself, you should at least force equal aspect ratio for axes with asp = 1 in your plot call. So the following should work:
## with metaMDS plot:
plot(mds1, display="si", las=1, type = "n") # for an empty plot
points(mds1, pch = as.numeric(bat$species), col= as.numeric(bat$species))
## or with generic plot:
plot(mds1$points[,1], mds1$points[,2], pch = as.numeric(bat$species),
col= as.numeric(bat$species),
xlab = "NMDS1", ylab= "NMDS2",
asp = 1, las = 1) # this is new

Plotting in R using plot function

I am trying to plot few graphs using loops. I am now describing in details.
First I have a function which is calculates the y-variable (called effect for vertical axis)
effect<- function (x, y){
exp(-0.35*log(x)
+0.17*log(y)
-0.36*sqrt(log(x)*log(y)/100))
}
Now I run the following code and use the option par to plot the lines in the same graph. I use axis=FALSE and xlab="" to get a plot without labels. I do this so that my labels are not re-written each time the loop runs and looks ugly.
for (levels in seq(exp(8), exp(10), length.out = 5)){
x = seq(exp(1),exp(10), length.out = 20)
prc= effect(levels,x)
plot(x, prc,xlim = c(0,max(x)*1.05), ylim=c(0.0,0.3),
type="o", xlab = "",ylab = "", pch = 16,
col = "dark blue", lwd = 2, cex = 1, axes = F)
label = as.integer(levels) #x variable
text(max(x)*1.03,max(prc), label )
par(new=TRUE)
}
Finally, I duplicate the plot command this time using the xlab and ylab options
plot(x, prc, xlab = "X-label", ylab = "effect",
xlim = c(0,max(x)*1.05), ylim = c(0,0.3),
type="l", col ='blue')
I have several other plots in the similar lines, using complex equations. I have two questions:
Is there an better option to have the same plot with smoother lines?
Is there an easier option with few lines to achieve the same, where I can place the texts (levels) for each line on the right with white background at the back?
I believe working with the plot function was tedious and time consuming. So, I have finally used ggplot2 to plot. There were several help available online, which I have used.

How to plot a Gamma distribution in ggplot2

I have a plot in R that I am trying to replicate in ggplot2. I have the following code:
theta = seq(0,1,length=500)
post <- dgamma(theta,0.5, 1)
plot(theta, post, type = "l", xlab = expression(theta), ylab="density", lty=1, lwd=3)
I have tried to replicate this plot in ggplot2 and this is the closest I was able to get.
df=data_frame(post,theta)
ggplot(data=df,aes(x=theta))+
stat_function(fun=dgamma, args=list(shape=1, scale=.5))
You didn't match up your parameters correctly. The signature of dgamma is
dgamma(x, shape, rate = 1, scale = 1/rate, log = FALSE)
so when you call
dgamma(theta, 0.5, 1)
that's
dgamma(theta, shape=0.5, rate=1)
which means you would translate the ggplot as
ggplot(data=df,aes(x=theta))+
stat_function(fun=dgamma, args=list(shape=0.5, rate=1))
you could also adjust the y-limits if you like with scale_y_continuous(limits=c(0,12)) or something similar.

Plot line of a function in R

I have the following script:
FGM = function (n,r,z){
x = r*sqrt(n)/(2*z)
Px = 1-pnorm(x)
}
re = 10000
data = data.frame(abs(rnorm(re,0,1)), abs(rnorm(re,0,1)), abs(rnorm(re,0,1)))
colnames(data) = c("n","r","z")
data$Px = FGM(data$n,data$r,data$z)
data$x = data$r*sqrt(data$n)/(2*data$z)
par(mar=c(4.5,4.5,1,1))
plot(data$x,data$Px, xlim = c(0,3), pch = 19, cex = 0.1, xaxs="i", yaxs="i",
xlab = expression(paste("Standardized mutational size (",italic(x), ")")),
ylab = expression(paste("P"[a],"(",italic(x),")")))
Which is a recreation of the graph found here (box 2). You can see in this script that I do this by just plotting 10000 small black points with various values of n,z, and r. This seems like an ugly work around, I think I should just be able to give R my function
FGM = function (n,r,z){
x = r*sqrt(n)/(2*z)
Px = 1-pnorm(x)
}
and have it plot a line on a graph. However, a few hours of scouring the web has been unproductive, and I tried a few ways with abline and lines but nothing worked, is there a way of doing it with these functions or another function?
Tried this...
plot(data$x,data$Px, xlim = c(0,3), ylim = c(0,0.5), xaxs="i", yaxs="i",
xlab = expression(paste("Standardized mutational size (",italic(x), ")")),
ylab = expression(paste("P"[a],"(",italic(x),")")), type = "n")
curve(1-pnorm(r*sqrt(n)/(2*z)), add=T)
>Error in curve(1 - pnorm(r * sqrt(n)/(2 * z)), add = T) :
'expr' must be a function, or a call or an expression containing 'x'
>
#PaulRegular offered this solution but it still plots based on data, not the formula itself. I'm looking for a solution which can produce the curve properly without large values of "re" - using the following but with "re" set to 10 you can see what I mean...
data <- data[order(data$x),]
lines(data$x, data$Px, lwd=1)
You can pass a function of just one variable to plot. I guess that you are looking for:
plot(function(x) 1-pnorm(x),0,3)
Try sorting your data by x, then add the line:
data <- data[order(data$x),]
lines(data$x, data$Px, lwd=2)

Customize minimum and maximum value for logi.hist.plot in R

Anybody know how to set the minimum and maximum values for x-axis when running logi.hist.plot in popbio package in R?
At the moment, the minimum value is defined as my minimum data value. I want it to be 0.
library(popbio)
logi.hist.plot(data$Heat, data$Death, logi.mod = 1,
boxp = FALSE,type="hist", col="gray",
ylabel = "Probability of death",
ylabel2 = "Death Frequency",
xlabel = "Heat",
mainlabel = "Logistic probability plot of Heat vs Death")
You have not offered a dataset for testing possible solutions to this request, but I offer an idea:
First make a plot that basically sets up the desired limits with xlim and ylim as desired, and blank x- and y-labels and axt="n",
...then issue par(new=TRUE),
...then run your plot function.
Taking a quick look at the source code - just type logi.hist.plot - it isn't possible to change the axis limits.
The source code is fairly long, but not that complicated. Essentially, the boxp=FALSE option calls this part of code:
logi.scater <- function(independ, depend, scater = "n", x.lab = xlabel,
las = las.h) {
plot(independ, depend, cex = 1, type = scater, ylab = ylabel,
xlab = x.lab, main = mainlabel, cex.lab = 1.2, las = las)
}
You can see that the plot function doesn't allow limits to be passed.
You options are:
Take apart the source code and construct your own plot.
Decided you are happy with the axis.

Resources