When I plot the density for wind direction using circular package, I get an error. The error is shown below. Can someone explain the bw (bandwidth) that I need for the amount of data?
plot(density(dirCir))
Error in density.circular(dirCir) :
argument "bw" is missing, with no default
This is the actual code that I have.
library (circular)
dir <-c(308,351,330,16,3,346,345,345,287,359,345,358,336,335,346,16,325,354,5,354,322,340,6,278,354,343,261,353,288,8)
dirCir <- circular(dir, units ="degrees", template = "geographics")
mean(dirCir)
var(dirCir)
summary(dirCir)
plot(dirCir)
plot(density(dirCir))
rose.diag(dirCir, main = 'dir Data')
points(dirCir)
As #eipi10 says, bw has to be explicitly chosen. Depending on the kernel that you choose large and small values of this bandwidth parameter may produce spiky density estimates as well as very smooth ones.
Common practice is to try several values and choose the one that seems to describe the data best. However, note that the following functions provide more objective ways of selecting the bw:
# bw.cv.mse.circular(dirCir)
[1] 21.32236
# bw.cv.mse.circular(dirCir, kernel = "wrappednormal")
[1] 16.97266
# bw.cv.ml.circular(dirCir)
[1] 19.71197
# bw.cv.ml.circular(dirCir, kernel = "wrappednormal")
[1] 0.2280636
# bw.nrd.circular(dirCir)
[1] 14.63382
When you run density on an object of class circular, it appears that you have to include a value for bw (bandwidth) explicitly (as the error message indicates). Try this:
plot(density(dirCir, kernel="wrappednormal", bw=0.02), ylim=c(-1,5))
See below for the graph. The ylim range is so that the plot fits inside the plot area without clipping. See the help for density.circular for more info on running the density function on circular objects.
Related
I am using the statspat package because I am working on spatial patterns.
I would like to do in ggplot and with colors instead of numbers (because it is not too readable),
the following graph, produced with the plot.quadratest function: Polygone
The numbers that interest me for the intensity of the colors are those at the bottom of each box.
The test object contains the following data:
Test object
I have looked at the help of the function, as well as the code of the function but I still cannot manage it.
Ideally I would like my final figure to look like this (maybe not with the same colors haha):
Final object
Thanks in advance for your help.
Please provide a reproducible example in the future.
The package reprex may be very helpful.
To use ggplot2 for this my best bet would be to convert
spatstat objects to sf and do the plotting that way,
but it may take some time. If you are willing to use base
graphics and spatstat you could do something like:
library(spatstat)
# Data (using a built-in dataset):
X <- unmark(chorley)
plot(X, main = "")
# Test:
test <- quadrat.test(X, nx = 4)
# Default plot:
plot(test, main = "")
# Extract the the `quadratcount` object (regions with observed counts):
counts <- attr(test, "quadratcount")
# Convert to `tess` (raw regions with no numbers)
regions <- as.tess(counts)
# Add residuals as marks to the tessellation:
marks(regions) <- test$residuals
# Plot regions with marks as colors:
plot(regions, do.col = TRUE, main = "")
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/
I have a bit of R-code to make a heatmap from a correlation matrix, which worked the last time I used it (prior to the 2013 Oct 17 update of gplots; after updating to R Version 3.0.2). This makes me think that something changed in the most recent gplots update, but I can not figure out what.
What used to present a nice plot now gives me this error:
" Error in hclustfun(distfun(x)) : could not find function "distfun" "
and won't plot anything. Below is the code to reproduce the plot (heavily commented as I was using it to teach an undergrad how to use heatmaps for a project). I tried adding the last line to explicitly set the functions, but it didn't help resolve the problem.
EDIT: I changed the last line of code to read:
,distfun =function(c) {as.dist(1-c,upper=FALSE)}, hclustfun=hclust)
and it worked. When I used just "dist=as.dist" I got a plot, but it wasn't sorted right, and several of the dendrogram branches didn't connect to the tree. Not sure what happened, or why this is working, but it appears to be.
Any help would be greatly appreciated.
Thanks in advance,
library(gplots)
set.seed(12345)
randData <- as.data.frame(matrix(rnorm(600),ncol=6))
randDataCorrs <- randData+(rnorm(600))
names(randDataCorrs) <- paste(names(randDataCorrs),"_c",sep="")
randDataExtra <- cbind(randData,randDataCorrs)
randDataExtraMatrix <- cor(randDataExtra)
heatmap.2(randDataExtraMatrix, # sets the correlation matrix to use
symm=TRUE, #tells whether it is symmetrical or not
main= "Correlation matrix\nof Random Data Cor", # Names plot
xlab= "x groups",ylab="", # Sets the x and y labels
scale="none", # Tells it not to scale the data
col=redblue(256),# Sets the colors (can be manual, see below)
trace="none", # tells it not to add a trace
symkey=TRUE,symbreaks=TRUE, # Tells it to keep things symmetric around 0
density.info = "none"#) # can be "histogram" if you want a hist of your corr values here
#,distfun=dist, hclustfun=hclust)
,distfun =function(c) {as.dist(1-c,upper=FALSE)}, hclustfun=hclust) # new last line
I had the same error, then I noticed that I had made a variable called dist, which is the default call for distfun= dist. I renamed the variable and then everything ran fine. You likely made the same error, as your new code is working since you have altered the default call of distfun.
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
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.