Using panel.mathdensity and panel.densityplot in lattice graphics to plot Bayesian prior and posterior - r

I am trying to plot a Bayesian prior and posterior distribution using lattice graphics. I would like to have both distributions in one panel, for direct comparison.
I've tried different solutions all day, including qqmath but I didn't get them to work. Here's the attempt that has been most successful so far:
# my data
d <- dgamma(seq(from=0.00001,to=0.01,by=0.00001),shape = .1, scale = .01)
# my plot
densityplot(~d,
plot.points=FALSE,
panel = function(x,...) {
panel.densityplot(x,...)
panel.mathdensity(
dmath = dgamma,
args = list(shape = .1, scale=.01)
)
}
)
Even though the code runs through nicely, it doesn't do what I want it to. It plots the posterior (d) but not the prior.
I added stop("foo") to densityplot(...) to stop execution if an error occurs and I searched online for the error message:
Error in eval(substitute(groups), data, environment(formula)) : foo
But there are only a few results and they seem unrelated to me.
So, here's my question: Can anyone help me with this approach to achieve what I want?

I asked a similar question which leads to the same result. I got an answer and it was useful. You can find everything here

Related

How to change or reset parameters in the plot(ACF)-device within R-studio

I have estimated a two-intercept mixed multilevel-model using the function lme of the r-package nlme.
After that I checked for autocorrelation by visual inspection using the plot(ACF)-function.
Plotting for the first time I specified maxlag=16.
Now I have two problems: First, the maxlag parameter seems to be stuck somehow, i.e. further plots are all plotted with maxlag=16 even when maxlag is set to other values. 2. The plot is cropped at y=0.8 even if the value of lag 0 obviously is 1.
In the following I share the respective replex in hope of getting answers or inputs on how to solve these two issues.
Link to the dataset and if prefered to copy-paste to the following code-script as well:
#read.dataset:
datafclr <-read.csv("datafclr.csv", header = TRUE, sep = ",", dec = ".", fill = TRUE)
#required packages:
library("Matrix")
library("nlme")
#model-estimation:
tim2 <- lme(fixed=EERTmn ~ male + female +
(male:time7c) + (female:time7c) +
(male:IERT_Cp) + (female:IERT_Cp) +
(male:IERT_Cp_Partner) + (female:IERT_Cp_Partner)-1,
control=list(maxIter=100000), data=datafclr,
random=~male + female -1|dyade/female, correlation=corAR1(), na.action=na.omit)
summary(tim2)
#checking for autocorrelation:
plot(ACF(tim2, maxlag = 16), alpha = 0.01)
Results in the following plot:
This results in thin plot
When I change the maxlag:
plot(ACF(tim2, maxlag = 10), alpha = 0.01)
It results in the same plot
Many thanks in advance!
Best,
Patrick
Joes Schwartz helped me solve these issues in the R-Studio community. For the case someone will have the same difficulties I had I'm sharing his answers here:
First issue: maxlag needs to be typed maxLag and the function works fine.
Second issue: detailed help under the following link:
https://community.rstudio.com/t/resetting-plotting-settings-plot-acf-data/19441

How to control plot layout for lmerTest output results?

I am using lme4 and lmerTest to run a mixed model and then use backward variable elimination (step) for my model. This seems to work well. After running the 'step' function in lmerTest, I plot the final model. The 'plot' results appear similar to ggplot2 output.
I would like to change the layout of the plot. The obvious answer is to do it manually myself creating an original plot(s) with ggplot2. If possible, I would like to simply change the layout of of the output, so that each plot (i.e. plotted dependent variable in the final model) are in their own rows.
See below code and plot to see my results. Note plot has three columns and I would like three rows. Further, I have not provided sample data (let me know if I need too!).
library(lme4)
library(lmerTest)
# Full model
Female.Survival.model.1 <- lmer(Survival.Female ~ Location + Substrate + Location:Substrate + (1|Replicate), data = Transplant.Survival, REML = TRUE)
# lmerTest - backward stepwise elimination of dependent variables
Female.Survival.model.ST <- step(Female.Survival.model.1, reduce.fixed = TRUE, reduce.random = FALSE, ddf = "Kenward-Roger" )
Female.Survival.model.ST
plot(Female.Survival.model.ST)
The function that creates these plots is called plotLSMEANS. You can look at the code for the function via lmerTest:::plotLSMEANS. The reason to look at the code is 1) to verify that, indeed, the plots are based on ggplot2 code and 2) to see if you can figure out what needs to be changed to get what you want.
In this case, it sounds like you'd want facet_wrap to have one column instead of three. I tested with the example from the **lmerTest* function step help page, and it looks like you can simply add a new facet_wrap layer to the plot.
library(ggplot2)
plot(Female.Survival.model.ST) +
facet_wrap(~namesforplots, scales = "free", ncol = 1)
Try this: plot(difflsmeans(Female.Survival.model.ST$model, test.effs = "Location "))

Label outliers using mvOutlier from MVN in R

I'm trying to label outliers on a Chi-square Q-Q plot using mvOutlier() function of the MVN package in R.
I have managed to identify the outliers by their labels and get their x-coordinates. I tried placing the former on the plot using text(), but the x- and y-coordinates seem to be flipped.
Building on an example from the documentation:
library(MVN)
data(iris)
versicolor <- iris[51:100, 1:3]
# Mahalanobis distance
result <- mvOutlier(versicolor, qqplot = TRUE, method = "quan")
labelsO<-rownames(result$outlier)[result$outlier[,2]==TRUE]
xcoord<-result$outlier[result$outlier[,2]==TRUE,1]
text(xcoord,label=labelsO)
This produces the following:
I also tried text(x = xcoord, y = xcoord,label = labelsO), which is fine when the points are near the y = x line, but might fail when normality is not satisfied (and the points deviate from this line).
Can someone suggest how to access the Chi-square quantiles or why the x-coordinate of the text() function doesn't seem to obey the input parameters.
Looking inside the mvOutlier function, it looks like it doesn't save the chi-squared values. Right now your text code is treating xcoord as a y-value, and assumes that the actual x value is 1:2. Thankfully the chi-squared value is a fairly simple calculation, as it is rank-based in this case.
result <- mvOutlier(versicolor, qqplot = TRUE, method = "quan")
labelsO<-rownames(result$outlier)[result$outlier[,2]==TRUE]
xcoord<-result$outlier[result$outlier[,2]==TRUE,1]
#recalculate chi-squared values for ranks 50 and 49 (i.e., p=(size:(size-n.outliers + 1))-0.5)/size and df = n.variables = 3
chis = qchisq(((50:49)-0.5)/50,3)
text(xcoord,chis,label=labelsO)
As it is mentioned in the previous reply, MVN packge does not support to label outliers. Although it is not really necessary since it can be done manually, we still might consider to add "labeling outliers" option within mvOutlier(...) function. Thanks for your interest indeed. We might include it in the following updates of the package.
The web-based version of the MVN package has now ability to label outliers (Advanced options under Outlier detection tab). You can access this web-tool through http://www.biosoft.hacettepe.edu.tr/MVN/

r - Add text to each lattice histogram with panel.text but has error "object x is missing"

In the following R code, I try to create 30 histograms for the variable allowed.clean by the factor zip_cpt(which has 30 levels).
For each of these histograms, I also want to add mean and sample size--they need to be calculated for each level of the factor zip_cpt. So I used panel.text to do this.
After I run this code, I had error message inside each histogram which reads "Error using packet 21..."x" is missing, with..." (I am not able to read the whole error message because they don't show up in whole). I guess there's something wrong with the object x. Is it because mean(x) and length(x) don't actually apply to the data at each level of the factor zip_cpt?
I appreciate any help!
histogram(~allowed.clean|zip_cpt,data=cpt.IC_CAB1,
type='density',
nint=100,
breaks=NULL,
layout=c(10,3),
scales= list(y=list(relation="free"),
x=list(relation="free")),
panel=function(x,...) {
mean.values <-mean(x)
sample.n <- length(x)
panel.text(lab=paste("Sample size = ",sample.n))
panel.text(lab=paste("Mean = ",mean.values))
panel.histogram(x,col="pink", ...)
panel.mathdensity(dmath=dnorm, col="black",args=list(mean=mean(x, na.rm = TRUE),sd=sd(x, na.rm = TRUE)), ...)})
A discussion I found online is helpful for adding customized text (e.g., basic statistics) on each of the histograms:
https://stat.ethz.ch/pipermail/r-help/2007-March/126842.html

What does negative length vectors in a wireframe plot (lattice package) means?

I want to plot a wireframe in R using the lattice package. However, I get the following error message "error using packet 1 negative length vectors are not allowed". The data looks like the following:
> result_mean
experiment alpha beta packet
1 0 1.0 1 3.000000
2 0 1.1 1 2.571429
The command to create the data is the following
png(file=paste("foobar.png"),width=1280, height=1280);
plot <- wireframe(result_mean$packet ~ result_mean$alpha * result_mean$beta,
data=result_mean, scales = list(arrows=FALSE, cex= .45, col = "black", font = 3),
drape = TRUE, colorkey = TRUE, main = "Foo",
col.regions = terrain.colors(100),
screen = list(z = -60, x = -60),
xlab="alpha", ylab="beta", zlab="mean \npackets");
print(plot);
dev.off();
I'm wondering what this error message means and if there is a good way to debug this?
Thanks in advance!
Debugging lattice graphics is a bit difficult because (a) the code is complex and multi-layered and (b) the errors get trapped in a way that makes them hard to intercept. However, you can at least get some way in diagnosing the problem.
First create a minimal example. I suspected that your problem was that your data fall on a single line, so I created data that looked like that:
d <- data.frame(x=c(1,1.1),
y=c(1,1),
z=c(2,3))
library(lattice)
wireframe(z~y*x,data=d)
Now confirm that fully three-dimensional data (data that define a plane) work just fine:
d2 <- data.frame(expand.grid(x=c(1,1.1),
y=c(1,1.1)),
z=1:4)
wireframe(z~y*x,data=d2)
So the question is really -- did you intend to draw a wireframe of two points lying on a line? If so, what did you want to have appear in the plot? You could hack things a little bit to set the y values to differ by a tiny bit -- I tried it, though, and got no wireframe appearing (but no error either).
edit: I did a bit more tracing, with various debug() incantations (and searching the source code of the lattice package and R itself for "negative length") to deduce the following: within a function called lattice:::panel.3dwire, there is a call to a C function wireframePanelCalculations, which you can see at https://r-forge.r-project.org/scm/viewvc.php/pkg/src/threeDplot.c?view=markup&root=lattice
Within this function:
nh = (nx-1) * (ny-1) * ng; /* number of quadrilaterals */
sHeights = PROTECT(allocVector(REALSXP, nh));
In this case nx is zero, so this code is asking R to allocate a negative-length vector, which is where the error comes from.
In this case, though, I think the diagnosis is more useful than the explicit debugging.

Resources