How can I increase the map size in a plot? - r

I want to plot points in an openstreetmap. To determine a suitable range for the map I want to use min() and max() and increase the size by 10%:
library(OpenStreetMap)
coords <- data.frame(cbind(c(-2.121821, -2.118570, -2.124278),
c(51.89437, 51.90330, 51.90469)))
topleft <- c(max(coords[,2]) + 0.1 * max(coords[,2]),
min(coords[,1]) - 0.1 * min(coords[,1]))
bottomright <- c(min(coords[,2]) - 0.1 * min(coords[,2]),
max(coords[,1]) + 0.1 * max(coords[,1]))
map <- openproj(openmap(topleft, bottomright, zoom = "16", type="osm"))
When I now try to create the map R eats up all my resources and I have to kill the process. Is there a better way to achieve this?
R version 3.0.1 (2013-05-16)
Platform: x86_64-unknown-linux-gnu (64-bit)
other attached packages:
[1] ggplot2_0.9.3.1 OpenStreetMap_0.3.1 rgdal_0.8-14 raster_2.2-12 sp_1.0-14
[6] rJava_0.9-6

You're extending the range incorrectly, as you'll see if you have a look at the computed values of topleft and bottomright.
A less error-prone approach might use the function extendrange() (which is used by many R plotting functions to add a little buffer around the most extreme points in the plot).
xx <- extendrange(coords[[1]], f=0.10)
yy <- extendrange(coords[[2]], f=0.10)
tl <- c(max(yy), min(xx))
br <- c(min(yy), max(xx))
map <- openproj(openmap(tl, br, zoom="16", type="osm"))
plot(map)

Related

Rasterize SpatVect (points) with buffer around SpatRaster

I have a SpatVect consisting of points and I want to rasterize them into a SpatRaster with a given resolution. Is there a way of specifying a function taking in the points that are within a buffer of each raster cell?
Many thanks
Joao
-- Update --
Maybe a figure would help understand what I'm after with my question. The red square will have to be run over the center of each pixel to calculate some statistics using the ovelaying points. Apologies for the clumsy question, but I hope the figure is clear enough...
terra version 1.6-28 supports rasterization of points with a rectangular moving window.
Example data
library(terra)
#terra 1.6.33
r <- rast(ncol=100, nrow=100, crs="local", xmin=0, xmax=50, ymin=0, ymax=50)
set.seed(100)
x <- runif(50, 5, 45)
y <- runif(50, 5, 45)
z <- sample(50)
v <- vect(data.frame(x,y,z), geom=c("x", "y"))
Solution
r1 <- rasterizeWin(v, r, field="z", fun="count", pars=10, win="rectangle")
plot(r1)
points(x, y)
You can change fun to another function that works for you, and you can change the size of the moving window with pars.
Instead of a rectangle, you can also use a circle or an ellipse. The border of a circular window is equidistant from the center of the cells. In contrast, the border of rectangles are at a constant distance from the border of the grid cells in most directions (not at the corners). Here is an example.
r2 <- rasterizeWin(v, r, field="z", fun="count", pars=5.25, win="circle")
plot(r2)
You can also use buffers around each cell to get a window that is truly equidistant from each cell border.
r3 <- rasterizeWin(v, r, field="z", fun=length, pars=5, win="buf")
plot(r3)
In this case, because the buffer size is large relative to the cell size, the result is very similar to what you get when using a circular window. Using "circle" should be the fastest, and using "buffer" should be the slowest in most cases. The function should now in all cases be memory-safe, except, perhaps when using very large buffers (more could be done if need be).
Version 1.6-28 is currently the development version. You can install it with
install.packages('terra', repos='https://rspatial.r-universe.dev')
The approach you take seems to depend on what result you're looking for from the above and the relationship they have with each other.
library(terra)
`terra::buffer(` # both SpatVectx/SpatRastery, to distance in 'm'
`terra::buffer(` # that is meaningful
#take Rasty to SpatVecty
`terra::as.polygons(`, #then
`z<-terra::intersection(SpatVectx, SpatVecty)`
then back to SpatRastz? terra::mask or crop, might also be useful, again depending on where things are going next.

How to generate a negative exponential distribution in R

I was manually creating a negative exponent distribution today and was trying to figure out a faster/easier solution. First, I just manually crafted a geometric sequence such as this one, multiplying constantly by .60 til I neared zero:
x <- 400
x*.60
Doing this about 20 times, I got this vector of solutions and plotted the distribution, as seen below:
y <- c(400,240,144,86.4, 51.84, 31.104, 18.6624, 11.19744, 6.718464, 4.031078,
2.418647, 1.451188, .8707129, .5224278, .3134567, .188074, .1128444,
.06770664, .04062398, .02437439)
plot(y)
However, I was trying to figure out what must be an easier way of doing this with seq, but I only know how to do this with arithmetic sequences. I tried reproducing what I did below:
plot(seq(from=400,
to=1,
by=-.60))
Which obviously doesn't produce the same effect, causing a very linear decline when plotted:
Is there an easier solution? I have to imagine that this is a rather basic function within R.
You may use dexp.
(x <- dexp(1:20, rate=.5)*1000)
# [1] 303.26532986 183.93972059 111.56508007 67.66764162 41.04249931 24.89353418 15.09869171 9.15781944 5.55449827
# [10] 3.36897350 2.04338572 1.23937609 0.75171960 0.45594098 0.27654219 0.16773131 0.10173418 0.06170490
# [19] 0.03742591 0.02269996
plot(x)
To make it start exactly at 400, we can minimize (400 - dexp(1, rate=.5)*x)^2 using optimize.
f <- function(x, a) (a - dexp(1, rate=.5)*x)^2
xmin <- optimize(f, c(0, 4000), a=400)
(x <- dexp(seq_len(20), rate=.5)*xmin$minimum)
# [1] 400.00000000 242.61226389 147.15177647 89.25206406 54.13411329 32.83399945 19.91482735 12.07895337 7.32625556
# [10] 4.44359862 2.69517880 1.63470858 0.99150087 0.60137568 0.36475279 0.22123375 0.13418505 0.08138735
# [19] 0.04936392 0.02994073
Note that if you want any different rate= you should to use it both in optimize and when creating the values.

EBImage feature names

Can anyone explain what is being used to compute different features within computeFeatures?
I get the naming convention being applied that is spelled out in ? computeFeatures. I don't understand the .0., .a. and .Ba. labels.
For example:
> library(EBImage)
> y = readImage(system.file("images", "nuclei.tif", package="EBImage"))[,,1]
> x = thresh(y, 10, 10, 0.05)
> x = opening(x, makeBrush(5, shape='disc'))
> x = bwlabel(x)
> ft = computeFeatures(x, y, xname="nucleus")
> colnames(ft)
[1] "nucleus.0.m.cx" "nucleus.0.m.cy"
[3] "nucleus.0.m.majoraxis" "nucleus.0.m.eccentricity"
<snip>
[11] "nucleus.0.s.radius.max" "nucleus.a.b.mean"
[13] "nucleus.a.b.sd" "nucleus.a.b.mad"
<snip>
[51] "nucleus.Ba.b.mean" "nucleus.Ba.b.sd"
[53] "nucleus.Ba.b.mad" "nucleus.Ba.b.q001"
[55] "nucleus.Ba.b.q005" "nucleus.Ba.b.q05"
<snip>
My guess is nucleus.0.* features use only the data from the binary masks contained in x. So nucleus.0.m.cy is the y-axis centroid computed using the binary data. There are also nucleus.a.m.cy and nucleus.Ba.m.cy but it is unclear how these computations are different (they are extremely correlated but not identical).
I also suppose the .a. and .Ba. use the intensity values in y but the details are vague. Features like nucleus.a.b.mean and nucleus.Ba.b.mean are similar (~.80 corr) but not the same. I assume that they estimate the mean y intensity of objects defined by the labels in x but the difference is unclear.
Is there any documentation on this?
Thanks,
Max
> sessionInfo()
R Under development (unstable) (2014-08-23 r66461)
Platform: x86_64-apple-darwin10.8.0 (64-bit)
locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8
attached base packages:
[1] stats graphics grDevices utils datasets methods base
other attached packages:
[1] EBImage_4.7.16
loaded via a namespace (and not attached):
[1] abind_1.4-0 BiocGenerics_0.11.4 grid_3.2.0
[4] jpeg_0.1-8 lattice_0.20-29 locfit_1.5-9.1
[7] parallel_3.2.0 png_0.1-7 tiff_0.1-5
[10] tools_3.2.0
Have you seen the documentation here: AnalysisWithEBImage
This seems to be the most in depth document that discusses the package. Have you tried contacting the author Grégoire Pau directly? Im sure if you google him you can find him.
As a disclaimer, I know nothing of your field, but by looking at the function I can make a pretty good guess at what is going on. I recommend that you use debugonce(computeFeatures) and then run ft = computeFeatures(x, y, xname="nucleus"). You can step through each line of the code (type Q) to exit, and see what is going on.
As you noted, the documentation states:
Features are named x.y.f, where x is the object layer, y the
reference image layer and f the feature name.
In your example computeFeatures has generated values for three reference layers (a, aB, and 0). The documentation mentions that if you don't name your reference layers, they will just be given the letters of the alphabet, so in your case you had one reference layer, and it is called a. I believe the 0 means that it uses no reference layer.
From looking at the source code, it appears that for every layer i, a B_i layer is created. It appears to pass a hardcoded filter over each layer as you can see in this code, found in the expandRef function (the comments are mine):
# Hard code a filter
blob = gblob(x0 = 15, n = 49, alpha = 0.8, beta = 1.2)
# Filter using the fast 2D FFT convolution product.
bref = lapply(ref, function(r) filter2(r, blob)/2)
# Name it "B" and then the layer name
names(bref) = paste("B", names(ref), sep = "")
I don't know exactly what you are trying to do here, but you can see visually what this filter is doing. Here is your x (you can just run display(x) to see it):
Here is your reference (y):
Here is what the hardcoded filter looks like:
And this is what the hardcoded filter does to y:
So, to summarize: everything with 0 is comparing to a no reference, everything with a is comparing directly to y as a reference, and everything with aB is comparing to a filtered version of y.

How to map wind direction and speed (velocity plot) with R

Basically I have lists with 2 matrices (u and v) containing the windspeed in longitudal and latitudal direction (and vectors x and y containing the coordinates). I would like to make a map with arrows pointing in the resulting direction, of which the size is proportional to the wind speed. This question was asked before: http://www.mail-archive.com/r-help#r-project.org/msg18875.html.
Uforunately, the link given in the answer is broken. I tried using the quiver function, but I don't get it working.
Here is how my data looks like:
x=seq(10,15,by=0.25)
y=seq(40,50,by=0.25)
u=matrix(runif(length(x)*length(y),-2,3),nrow=length(y),ncol=length(y))
v=matrix(runif(length(x)*length(y),-2,3),nrow=length(y),ncol=length(y))
wind=list(u,v)
For the quiver function:
library(pracma)
quiver(x=x, y=y, u=wind[[1]], v=wind[[2]])
Which gives twice:
Error: invalid graphics state
I assume that u and v are wrong and need to be coordinates as well, but I honestly don't understand the explanation given in the package discription (u, v : x,y-coordinates of start points).
I saw that more info is available for quiver in matlab or python, but I never worked with that, so any advice about doing this in R would be greatly appreciated.
x=seq(10,15,by=0.25)
y=seq(40,50,by=0.25)
u=matrix(runif(length(x)*length(y),-2,3),nrow=length(x),ncol=length(y))
v=matrix(runif(length(x)*length(y),-2,3),nrow=length(x),ncol=length(y))
#note that I corrected these
#melt for plotting
library(reshape2)
u <- melt(u,value.name = "u")
v <- melt(v,value.name = "v")
wind <- merge(u, v)
wind$x <- x[wind[,1]]
wind$y <- y[wind[,2]]
#plot
library(ggplot2)
library(grid)
scaler <- 1
p <- ggplot(wind, aes(x=x, y=y, xend=x+u*scaler, yend=y+v*scaler)) + geom_segment(arrow=arrow())
print(p)

Convert units from npc to native using grid in R

The core of my problem:
I'm attempting to convert npc units to native units using the grid package's convertUnit, convertX and convertY functions. (npc=normalized parent coordinates, possibly known as ndc units, normalized device coordinates to some in base graphics R. I'm trying to get to native units, those in which the plot is graphed, so in terms of the xlim and ylim units.) However when I attempt to do this as such:
> xyplot(1:10~1:10)
> convertX(unit(.9, "npc"), "native")
[1] 484.2native
when I'm expecting a number close to 9 as the native x coordinate. It appears convertX is returning units in device coordinates/pixels instead.
Reasoning:
I'm trying to use a base locator type device to return npc coordinates, and from those npc coordinates convert to the native coordinates in which the graph was plotted. While I can use base graphics' locator or grid.locator, I'm trying to extend the functionality of this new, non blocking locator to grid/lattice graphics by converting from npc back to native. convertUnit and convertY don't work either.
Question
Is it possible for grid to convert from npc back to the active plotting window's native coordinates? Why is convertX returning pixels rather than native coordinates?
Thanks much in advance.
Edited for tags and sloppy mistake leaving out xyplot before. My apologies, but it holds with xyplot.
‘"native"’ Locations and dimensions are relative to the viewport's ‘xscale’ and ‘yscale’.
The conversions occur within the current viewport.
> plot(1:10)
> convertX(unit(.9,"npc"),"native")
[1] 453.6native
> pushViewport(viewport())
> convertX(unit(.9,"npc"),"native")
[1] 0.9native
> convertX(unit(.1,"npc"),"picas")
[1] 4.21575picas #making window smaller
> convertX(unit(.1,"npc"),"picas")
[1] 1.9798375984252picas #making window larger
> convertX(unit(.1,"npc"),"picas")
[1] 5.25783218503937picas
So you need a viewport first to get sensible values out.
Apparently, after the viewport is pushed, it has forgotten about the set coordinate of the underlying plot and the new coordinates seem to be equivalent to the npc coordinates.
Until you plot into the new viewport, after which you are back to square one:
xyplot(1:10 ~ 10:1)
> convertX(unit(.9, "npc"), "native")
[1] 605.7native
> pushViewport(viewport())
> convertX(unit(.9, "npc"), "native")
[1] 0.9native
> xyplot(1:10 ~ 10:1)
> convertX(unit(.9, "npc"), "native")
[1] 605.7native
Is it possible to obtain coordinates that correspond to those in which x and y are actually plotted?

Resources