I'm trying to create a good heat map using Krigging for missing values.
I have the following data, that contains all the values that have been measured for RLevel.
I followed the following link that tells how to use krigging. https://rpubs.com/nabilabd/118172
This is the following code I wrote. Before these steps, I had removed all the values from my DieData that
needed values to be tested. The values that need to be tested are refered as die.data.NAValues in my code.
#**************************************************CODE*****************
#Step3: Convert to SpatialPointsDataFrame Object
coordinates(die.data) = ~X+Y
#Step 4: Get the prediction Grid
coordinates(die.data.NAValues)=~X+Y
#Using autokride method
kr = autoKrige(RLevel, die.data, die.data.NAValues,nmax=20)
predicted_die_values <- kr$krige_output
predicted_die_model <- kr$var_model
#Get Predictions. Plot the predicted on heat map.
g <- gstat(NULL,"RLevel",RLevel~1,die.data, model=predicted_die_model,nmax=1)
predictedSet <- predict(g,newdata=die.data,BLUE=TRUE)
#Plot the krigging graph
predicted_die_values %>% as.data.frame %>% ggplot(aes(x=X,y=Y)) + geom_tile(aes(fill=v1.pred))+coord_equal() +scale_fill_gradient(low="yellow",high="red")+scale_x_continuous()+scale_y_continuous()+theme_bw()
When I plot the graph, I get the following image from the values that have been tested by the KRIGING METHOD.
My question is how can I show a good heat map with predicted points from KRIG and from the points already have. I want my graph to show something like this from the link above I had posted.
Description about my dataset: My original dataset including NA values that have not been tested contains around 55057 points. When I take out NA values and use that are my prediction grid, I get 390 points. Majority of the values for RLevel are within 30's range except around 100-200 points are above 100.
Can anyone help me out or give me guidance of how to produce a good heatmap?
Related
I have a raster file, which I created from data downloaded from DIVA-GIS: http://www.diva-gis.org/datadown
nz_map<-raster("NZL1_msk_cov.grd")
Using plot() on this object works great, so there are no issues importing it. The raster object contains a lot of data I don't need, data on land cover. I want a more simple raster object with lon & lat coordinates and a value of 1 for land and NA for ocean.
This raster will be used with the dismo function randomPoints() to sample background data for modelling species distribution, so the most important thing is to identify which areas are land(suitable for sampling) and which are ocean(unsuitable).
I can visualise the raster more simply with plot(!is.na(nz_map5)). This works well and services for the randomPoints() function, but I'm not sure how to edit the color of the map. Doing this: plot(!is.na(nz_map5), col="grey") results in a totally grey block, instead of just colouring the appropriate areas grey; this is why I thought I might be better off with a more simple raster object, to do away with the !is.na argument Any ideas?
If anyone knows of a place you could download such files, saving me the hassle- that works, too.
Here are similar data for elevation
library(raster)
a <- getData("alt", country="NZL")
r <- a[[1]]
plot(r)
I think your confusion stems from what happens here
x <- !is.na(r)
That turns the values to TRUE (those that were not NA) or FALSE (those that were NA). So now you have two categories
plot(x, col=c("red", "blue"))
And now it is no longer a good dataset for dismo::randomPoints
If you would rather have NA and 1 other value you can do
y <- r * 0
plot(y, col="blue")
Or
y <- reclassify(y, cbind(-Inf, Inf, 1))
But, as you say yourself, for randomPoints you can just use the original data.
I've just started learning R, and was wondering, say I have the dataset quake, and I want to generate the probability histogram of quakes near Fiji, would the code simply be hist(quakes$lat,freq=F)?
A histogram shows the frequency or proportion of a given value out of all the values in a data set. You need a numeric vector as the x argument for hist(). There is no flat variable in quakes, but there is a lat variable. hist(quakes$lat, freq = F) would show the following:
This shows the north/south geographical distribution of earthquakes, centering around -20, and, since it is approximately normal (with a left skew) suggests that there is a mechanism for earthquake generation that centers around a specific latitude.
The best way to learn is to try. If you wonder if that would be the way to do it, try it.
You might also want to look at this tutorial on creating kernel density plots with ggplot.
I have a set of coordinates X and Y for my points and used the deldir to create determine and plot the Voronoi Polygons. (I've used this tutorial here)
This is my plot: (sorry that its so small, but you get the idea).
I need to determine the area of each polygon. How can I do that?
I looked up in the deldirpackage page and couldnt find anything related to the Voronoi polygons, only about other
Based on the reference manual (https://cran.r-project.org/web/packages/deldir/index.html), the output of the deldir function is a list. One of the list element, summary, is a data frame, which contains a column called dir.area. This is the the area of the Dirichlet tile surrounding the point, which could be what you are looking for.
Below I am using the example from the reference manual. Use $ to access the summary data frame.
library(deldir)
x <- c(2.3,3.0,7.0,1.0,3.0,8.0)
y <- c(2.3,3.0,2.0,5.0,8.0,9.0)
dxy1 <- deldir(x,y)
dxy1$summary
I am using the ks package from R to estimate 2d space utilization using distance and depth information. What I would like to do is to use the 95% contour output to get the maximum vertical and horizontal distance. So essentially, I want to be able to get the dimensions or measurements of the resulting 95% contour.
Here is a piece of code with as an example,
require(ks)
dist<-c(1650,1300,3713,3718)
depth<-c(22,19.5,20.5,8.60)
dd<-data.frame(cbind(dist,depth))
## auto bandwidth selection
H.pi2<-Hpi(dd,binned=TRUE)*1
ddhat<-kde(dd,H=H.pi2)
plot(ddhat,cont=c(95),lwd=1.5,display="filled.contour2",col=c(NA,"palegreen"),
xlab="",ylab="",las=1,ann=F,bty="l",xaxs="i",yaxs="i",
xlim=c(0,max(dd[,1]+dd[,1]*0.4)),ylim=c(60,-3))
Any information about how to do this will be very helpful. Thanks in advance,
To create a 95% contour polygon from your 'kde' object:
library(raster)
im.kde <- image2Grid (list(x = ddhat$eval.points[[1]], y = ddhat$eval.points[[2]], z = ddhat$estimate))
kr <- raster(im.kde)
It is likely that one will want to resample this raster to a higher resolution before constructing polygons, and include the following two lines, before creation of the polygon object:
new.rast <- raster(extent(im.kde),res = c(50,50))
kr <- resample(kr, new.rast)
bin.kr <- kr
bin.kr[bin.kr < contourLevels(k, prob = 0.05)]<-NA
bin.kr[bin.kr > 0]<-1
k.poly<-rasterToPolygons(bin.kr,dissolve=T)
Note that the results are similar, but not identical, to Hawthorne Beier's GME function 'kde'. He does use the kde function from ks, but must do something slightly different for the output polygon.
At the moment I'm going for the "any information" prize rather than attempting a final answer. The ks:::plot.kde function dispatches to ks:::plotkde.2d in this case. It works its magic through side effects and I cannot get these functions to return values that can be inspected in code. You would need to hack the plotkde.2d function to return the values used to plot the contour lines. You can visualize what is in ddhat$estimate with:
persp(ddhat$estimate)
It appears that contourLevels examines the estimate-matrix and finds the value at which greater than the specified % of the total density will reside.
> contourLevels(ddhat, 0.95)
95%
1.891981e-05
And then draws the contout based on which values exceed that level. (I just haven't found the code that does that yet.)
I have a set of 3D coordinates (below - just for a single point, in 3D space):
x <- c(-521.531433, -521.511658, -521.515259, -521.518127, -521.563416, -521.558044, -521.571228, -521.607178, -521.631165, -521.659973)
y <- c(154.499557, 154.479568, 154.438705, 154.398682, 154.580688, 154.365189, 154.3564, 154.559189, 154.341309, 154.344223)
z <- c(864.379272, 864.354675, 864.365479, 864.363831, 864.495667, 864.35498, 864.358582, 864.50415, 864.35553, 864.359863)
xyz <- data.frame(x,y,z)
I need to make a time-series plot of this point with a 3D rendering (so I can rotate the plot, etc.). The plot will visualize a trajectory of the point above in time (for example in the form of solid line). I used 'rgl' package with plot3d method, but I can't make it to plot time-series (below, just plot a single point from first frame in time-series):
require(rgl)
plot3d(xyz[1,1],xyz[1,2],xyz[1,3],axes=F,xlab="",ylab="",zlab="")
I found this post, but it doesn't really deal with a real-time rendered 3D plots. I would appreciate any suggestions. Thank you.
If you read help(plot3d) you can see how to draw lines:
require(rgl)
plot3d(xyz$x,xyz$y,xyz$z,type="l")
Is that what you want?
How about this? It uses rgl.pop() to remove a point and a line and draw them as a trail - change the sleep argument to control the speed:
ts <- function(xyz,sleep=0.3){
plot3d(xyz,type="n")
n = nrow(xyz)
p = points3d(xyz[1,])
l = lines3d(xyz[1,])
for(i in 2:n){
Sys.sleep(sleep)
rgl.pop("shapes",p)
rgl.pop("shapes",l)
p=points3d(xyz[i,])
l=lines3d(xyz[1:i,])
}
}
The solution was simpler than I thought and the problem was that I didn't use as.matrix on my data. I was getting error (list) object cannot be coerced to type 'double' when I was simply trying to plot my entire dataset using plot3d (found a solution for this here). So, if you need to plot time-series of set of coordinates (in my case motion capture data of two actors) here is my complete solution (only works with the data set below!):
download example data set
read the above data into a table:
data <- read.table("Bob12.txt",sep="\t")
extract XYZ coordinates into a separate matrixes:
x <- as.matrix(subset(data,select=seq(1,88,3)))
y <- as.matrix(subset(data,select=seq(2,89,3)))
z <- as.matrix(subset(data,select=seq(3,90,3)))
plot the coordinates on a nice, 3D rendered plot using 'rgl' package:
require(rgl)
plot3d(x[1:nrow(x),],y[1:nrow(y),],z[1:nrow(z),],axes=F,xlab="",ylab="",zlab="")
You should get something like on the image below (but you can rotate it etc.) - hope you can recognise there are joint centers for people there. I still need to tweak it to make it visually better - to have first frame as a points (to clearly see actor's joints), then a visible break, and then the rest of frames as a lines.