How to manipulate xlim and ylim to plot a map in r - r

For an assignment I'm working on, we are performing a distribution model using occurrence points. The plot that appears is showing an extent that is too large and I would like to change the xlim and ylim so that the plot is showing the area only with the occurrence points (orange area). I have tried manipulating it a few ways but it never focuses on the extent that I want. I guess what I really don't understand is what the xlim and ylim are specifying.
sparrow= gbif("ammodramus", "maritimus*", geo=FALSE)
sparrow <- subset(sparrow, !is.na(lon) & !is.na(lat))
library(maptools)
data(wrld_simpl)
plot(wrld_simpl, xlim=c(-80,70), ylim=c(-60,10), axes=TRUE, col="lightyellow")
points(sparrow$lon, sparrow$lat, col="orange", pch=20, cex=0.75)
points(acgeo$lon, acgeo$lat, col="red", cex=0.75)

When you do
library(sp)
coordinates(sparrow) = ~lon + lat
proj4string(sparrow) = proj4string(wrld_simpl)
plot(sparrow, col = 'red', cex = .75, axes = TRUE)
plot(wrld_simpl, add = TRUE)
the plot takes xlim and ylim from sparrow.

Related

How do I plot the coordinates of a spatial dataset when plotting it over a shapefile in R?

I am plotting a SpatialPointsDataFrame object of archaeological finds over a shapefile of the trench they were found in. So far I have managed to load and plot both sets of data together with:
coordinates(finds) <- ~x+y
trencharea <- readOGR(dsn="excpoly", layer="excpoly")
trencharea <- as.owin(trencharea)
plot(trencharea, main= "Trench & Finds")
plot(finds, add=TRUE, col = "blue", pch = 4)
However, I also want the x and y coordinates associated with the finds to be displayed on the x and y axes of my plot. How do I do this? I'm not looking for a solution that involves ggplot
I don't know if I understood correctly, are you looking for the following
plot(trencharea, main= "Trench & Finds")
plot(finds, add=TRUE, col = "blue", pch = 4)
axis(1)
axis(2)
box(col = 'black')
Dummy plot

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

Bid Rent Curves - Plotting Circles of Projected Radii from Another Dimension

The goal is to reproduce this Bid-Rent graph in R:
The challenge is to draw the projected circles. So far I got:
The 2D part is created by the R code below with the traditional graphic system in base R:
#Distance
X <- seq(0,7,1)
#Bid Rent Curves: Commercial, Industrial, Residential
com <- -5*X + 10
ind <- -2*X + 7
res <- -0.75*X + 4
graph <- plot(X, com, type="l", col="green", ylim=c(0,10), xlab="", ylab="", axes=FALSE)
lines(X, ind, col="red")
lines(X, res, col="blue")
abline(v=0, h=0)
segments(1,0, 1,5, lty=2)
segments(2.5,0, 2.5,2, lty=2)
title(main="Bid Rent Curves", sub="Alonso Model",
xlab="Distance from CBD", ylab="Rent per m2")
text(2.5,7.5, "Commercial", col="green")
text(3.5,4, "Industrial", col="red")
text(5.5,2, "Residential", col="blue")
(Detail: Why the curves do not respect the ylim = 0 ?)
How make the projection and draw the semi-circles?
It is not exactly a 3D plot. I have looked into plot3D and rgl. I am not sure which packages or strategy to use from here.
I'm taking you at your word that you want circles, so you need to push the plot area into the upper right corner:
outHalfCirc <- function(r,colr) {opar=par(xpd=TRUE, new=TRUE) #plot ouside plot area
polygon(x=seq(r,-r,by=-0.1),
y= -sqrt(r^2 - seq(r,-r,by=-0.1)^2) , # solve r^2 = x^2 +y^2 for y
xlim =c(0,7 ), ylim=c(0,10), col=colr, # need xlim and ylim to match base plot ranges
yaxs="i", yaxt="n", xaxs="i") # yaxis off; x and y axes meet at origin
par(opar)}
Then push plot up and to the right: This will draw a colored half-circles (largest first so they overlap) below the y=0 line.
png() # send to image file; not needed for testing
opar <- par(mar=c(15, 15, 2,2) ) # default units are in widths of text-"line".
# the margins start at lower, then clockwise
# run your code
outHalfCirc(5.5, "blue")
outHalfCirc(2.5, "red")
outHalfCirc(1, "green")
dev.off() # complete image production
par(opar) # different than the 'opar' inside the function
Voila! Although not really circles because the aspect ratio is not 1. That can be fixed (or you could set the xlim and ylim to be equal.

r spatial mapping

I am trying to make some nice spatial maps in R. I am trying to understand how to upload the data in case you would like to have a look at them but I have not figured that out (I am sorry for that but being a new user means looking for all these things).
What is my situation. I have a shapefile of the whole USA, I only need some states, and I can select my grid when I plot it (as you see from the code in the plot section).
I also have some yield data (points) which have latitude, longitude and Yield. I have 4 different Yield data which are called ("All Stations", "0.5", "1.0", and "2.0").
I am trying to plot these 4 yields data on the spatial map to have 4 different spatial maps. Which is done.
I have done this by reading on stackoverflow here and there I used bits and pieces to do that, although I have never done it before I was surprised how fast I could advance (Thank you people on StackOverflow!!!).
Can someone help me to understand if my code is correct?
Also, how can I make the legends of the 4 maps a regularr scale? E.g. from 4000 to 9000 with 500 intervals for each of the 4 maps. What I have done is to create a separate text file ("Yield for Legend.txt") which I use to generate the colour scales in the maps and the legends. Is that correct?
Again, your critics are mostly welcome!
Thank you,
David
rm(list=ls())
setwd("C:\\Users\\.....\\Shape File")
library(spatstat)
library(rgdal)
library(shapefiles)
library(maptools)
library(RColorBrewer)
library(classInt)
# read in shapefiles
counties.rg <- readOGR("C:\\Users\\......\\Shape File", "tl_2011_us_county")
Yields <- read.table("Yield.txt", skip=1, header = F)
Yield.g <- as.ppp(Yields, owin( c(-89, -76), c(25, 37)))
## Reading Data for Legend and colouring breaks
Y.LE <- read.table("Yield for Legend.txt", header=F)
Y.L.I <- classIntervals(Y.LE$V1, n=9, style = "quantile")
Y.L.I <- Y.L.I$brks
#select color palette and the number colors (levels of income) to represent on the map
#colors <- brewer.pal(9, "RdYlGn")
colors <- brewer.pal(9, "Greys")
################################################
### Generating MAPS ############################
################################################
#set breaks for the 9 colors
#par(mfrow=c(2,2))
pdf("13 August Spatial Maps.pdf")
# All Points
brks.all <-classIntervals(Yields$V3, n=9, style = "quantile")
brks.all <- brks.all$brks
plot(counties.rg, axes=TRUE, border="grey", xlim = c(-82, -80),
ylim = c(24, 37))
points(Yield.g, cex= 1.1, bg=colors[findInterval(Yields$V3, Y.L.I,all.inside=TRUE)], pch=21)
#add a title
title(paste ("Rainfed Yield (kg/ha)All Stations"))
#add a legend
legend("bottomright", legend=leglabs(round(Y.L.I)), fill=colors, bty="n", cex=0.7 ) #,x.intersp = .5, y.intersp = .5)
# 0.5 Grid
brks.05 <-classIntervals(Yields$V4, n=9, style = "quantile")
brks.05 <- brks.05$brks
plot(counties.rg, axes=TRUE, border="grey", xlim = c(-82, -80),
ylim = c(24, 37))
points(Yield.g, cex= 1.1, bg=colors[findInterval(Yields$V4, Y.L.I,all.inside=TRUE)], pch=21)
#abline(v=GF$V1, col="grey40")
#abline(h=GF$V2, col="grey10", lty="dotted")
#backup
#points(Yield.g, cex= Yields$V4/9000, col=colors[findInterval(Yields$V4, brks.05,all.inside=TRUE)], pch=19)
#add a title
title(paste ("Rainfed Yield (kg/ha)0.5"))
#add a legend
legend("bottomright", legend=leglabs(round(Y.L.I)), fill=colors, bty="n", cex=0.7 ) #,x.intersp = .5, y.intersp = .5)
# 1.0 Grid
brks.1 <-classIntervals(Yields$V5, n=9, style = "quantile")
brks.1 <- brks.1$brks
plot(counties.rg, axes=TRUE, border="grey", xlim = c(-82, -80),
ylim = c(24, 37))
points(Yield.g, cex= 1.1, bg=colors[findInterval(Yields$V5, Y.L.I,all.inside=TRUE)], pch=21)
#abline(v=GO$V1, col="grey40")
#abline(h=GO$V2, col="grey10", lty="dotted")
#add a title
title(paste ("Rainfed Yield (kg/ha)1.0"))
#add a legend
legend("bottomright", legend=leglabs(round(Y.L.I)), fill=colors, bty="n", cex=0.7 ) #,x.intersp = .5, y.intersp = .5)
# 2.0 Grid
brks.2 <-classIntervals(Yields$V6, n=9, style = "quantile")
brks.2 <- brks.2$brks
plot(counties.rg, axes=TRUE, border="grey", xlim = c(-82, -80),
ylim = c(24, 37))
points(Yield.g, cex= 1.1, bg=colors[findInterval(Yields$V6, Y.L.I,all.inside=TRUE)], pch=21)
#abline(v=GG$V1, col="grey40")
#abline(h=GG$V2, col="grey10", lty="dotted")
#add a title
title(paste ("Rainfed Yield (kg/ha)2.0"))
#add a legend
legend("bottomright", legend=leglabs(round(Y.L.I)), fill=colors, bty="n", cex=0.7 ) #,x.intersp = .5, y.intersp = .5)
dev.off()
In response to your specific query about setting the breaks and having your legend match, there is a fairly straightforward fix.
You use the classInterval function with style="quantile" to define your breaks. If you want the maps to show "from 4000 to 9000 with 500 intervals for each of the 4 maps" why not use style="fixed"
brks.all <-classIntervals(Yields$V3, n=10, style = "fixed",
fixedBreaks=seq(from=4000, to=9000, by=500)
brks.all <- brks.all$brks
Note that 4k to 9k by 500's creates 10 intervals by my count and 9 color gradations doesn't often make for a pretty map.
Alternatively, the dataPrecision variable within classInt may also help you get labels and breaks that are closer to what you want, but still based on quantiles (if not uniform across maps)

Axes at minimum extent, no padding, in plots of raster* objects

Is there a way to ensure that the box around a plot matches the raster extents exactly? In the following there is a gap above and below or to the left and right of the raster depending on the device proportions:
require(raster)
r = raster()
r[]= 1
plot(r, xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))
One element of the problem with raster objects is that asp=1 to ensure proper display. The following basic scatterplot has the same issue when asp=1:
plot(c(1:10), c(1:10), asp=1)
Try vectorplot(r) from the rasterVis package to see what I want the axes to look like.
EDIT:
Solutions need to play nice with SpatialPoints overlays, not showing points outside the specified raster limits:
require(raster)
require(maptools)
# Raster
r = raster()
r[]= 1
# Spatial points
x = c(-100, 0, 100)
y = c(100, 0, 100)
points = SpatialPoints(data.frame(x,y))
plot(r, xlim=c(xmin(r), xmax(r)), ylim=c(ymin(r), ymax(r)))
plot(points, add=T)
You'd probably do best to go with one of the lattice-based functions for plotting spatial raster objects provided by the raster and rasterVis packages. You discovered one of them in vectorplot(), but spplot() or levelplot() better match your needs in this case.
(The base graphics-based plot() method for "RasterLayer" objects just doesn't allow any easy way for you to set axes with the appropriate aspect ratio. For anyone interested, I go into more detail about why that's so in a section at the bottom of the post.)
As an example of the kind of plot that levelplot() produces:
require(raster)
require(rasterVis)
## Create a raster and a SpatialPoints object.
r <- raster()
r[] <- 1:ncell(r)
SP <- spsample(Spatial(bbox=bbox(r)), 10, type="random")
## Then plot them
levelplot(r, col.regions = rev(terrain.colors(255)), cuts=254, margin=FALSE) +
layer(sp.points(SP, col = "red"))
## Or use this, which produces the same plot.
# spplot(r, scales = list(draw=TRUE),
# col.regions = rev(terrain.colors(255)), cuts=254) +
# layer(sp.points(SP, col = "red"))
Either of these methods may still plot some portion of the symbol representing points that fall just outside of the plotted raster. If you want to avoid that possibility, you can just subset your SpatialPoints object to remove any points falling outside of the raster. Here's a simple function that'll do that for you:
## A function to test whether points fall within a raster's extent
inExtent <- function(SP_obj, r_obj) {
crds <- SP_obj#coord
ext <- extent(r_obj)
crds[,1] >= ext#xmin & crds[,1] <= ext#xmax &
crds[,2] >= ext#ymin & crds[,2] <= ext#ymax
}
## Remove any points in SP that don't fall within the extent of the raster 'r'
SP <- SP[inExtent(SP, r), ]
Additional weedy detail about why it's hard to make plot(r) produce snugly fitting axes
When plot is called on an object of type raster, the raster data is (ultimately) plotted using either rasterImage() or image(). Which path is followed depends on: (a) the type of device being plotted to; and (b) the value of the useRaster argument in the original plot() call.
In either case, the plotting region is set up in a way which produces axes that fill the plotting region, rather than in a way that gives them the appropriate aspect ratio.
Below, I show the chain of functions that's called on the way to this step, as well as the call that ultimately sets up the plotting region. In both cases, there appears to be no simple way to alter both the extent and the aspect ratio of the axes that are plotted.
useRaster=TRUE
## Chain of functions dispatched by `plot(r, useRaster=TRUE)`
getMethod("plot", c("RasterLayer", "missing"))
raster:::.plotraster2
raster:::.rasterImagePlot
## Call within .rasterImagePlot() that sets up the plotting region
plot(NA, NA, xlim = e[1:2], ylim = e[3:4], type = "n",
, xaxs = "i", yaxs = "i", asp = asp, ...)
## Example showing why the above call produces the 'wrong' y-axis limits
plot(c(-180,180), c(-90,90),
xlim = c(-180,180), ylim = c(-90,90), pch = 16,
asp = 1,
main = "plot(r, useRaster=TRUE) -> \nincorrect y-axis limits")
useRaster=FALSE
## Chain of functions dispatched by `plot(r, useRaster=FALSE)`
getMethod("plot", c("RasterLayer", "missing"))
raster:::.plotraster2
raster:::.imageplot
image.default
## Call within image.default() that sets up the plotting region
plot(NA, NA, xlim = xlim, ylim = ylim, type = "n", xaxs = xaxs,
yaxs = yaxs, xlab = xlab, ylab = ylab, ...)
## Example showing that the above call produces the wrong aspect ratio
plot(c(-180,180), c(-90,90),
xlim = c(-180,180), ylim = c(-90,90), pch = 16,
main = "plot(r,useRaster=FALSE) -> \nincorrect aspect ratio")
Man, I got stumped and ended up just turning the foreground color off to plot. Then you can take advantage of the fact that the raster plot method calls fields:::image.plot, which lets you just plot the legend (a second time, this time showing the ink!). This is inelegant, but worked in this case:
par("fg" = NA)
plot(r, xlim = c(xmin(r), xmax(r)), ylim = c(ymin(r), ymax(r)), axes = FALSE)
par(new = TRUE,"fg" = "black")
plot(r, xlim = c(xmin(r), xmax(r)), ylim = c(ymin(r), ymax(r)), axes = FALSE, legend.only = TRUE)
axis(1, pos = -90, xpd = TRUE)
rect(-180,-90,180,90,xpd = TRUE)
ticks <- (ymin(r):ymax(r))[(ymin(r):ymax(r)) %% 20 == 0]
segments(xmin(r),ticks,xmin(r)-5,ticks, xpd = TRUE)
text(xmin(r),ticks,ticks,xpd=TRUE,pos=2)
title("sorry, this could probably be done in some more elegant way")
This is way I solved this problem
require(raster)
r = raster()
# default for raster is 180 row by 360 cols = 64800 cells
# fill with some values to make more interesting
r[]= runif(64800, 1, 1000)
# Set margin for text
par(mar=c(2, 6, 6, 2))
# Set some controls for the raster cell colours and legend
MyBrks<-c(0,1,4,16,64,256,1E20)
MyLbls<-c("<1","<4","<16","<64","<256","<Max")
MyClrs<-c("blue","cyan","yellow","pink","purple","red")
# Plot raster without axes or box or legend
# Note xlim and ylim don't seem do much unless you want to trim x and y
plot(r,
col=MyClrs,
axes=FALSE,
box=FALSE,
legend=FALSE
)
# Set up the ranges and intervals for axes - you can get the min max
# using xmin(r) and ymax(r) and so on if you like
MyXFrm <- -180
MyXTo <- 180
MyXStp <- 60
MyYFrm <- -90
MyYTo <- 90
MyYStp <- 30
# Plot the axes
axis(1,tick=TRUE,pos=ymin(r),las=1,at=seq(MyXFrm,MyXTo ,MyXStp ))
axis(2,tick=TRUE,pos=xmin(r),las=1,at=seq(MyYFrm ,MyYTo ,MyYStp ))
# Plot the legend use xpd to plot the legend outside the plot region
par(xpd=TRUE)
legend(MyXTo ,MyYTo ,
legend=MyLbls[1:6],
col= MyClrs,
fill=Clrs[1:6],
bg=rgb(0,0,0,0.85),
cex=0.9,
text.col="white",
text.font=2,
border=NA
)
# Add some axis labels and a title
text(-220,0,"Y",font=2)
text(0,-130,"X",font=2)
text(0,120,"My Raster",font=4,cex=1.5)
I think the best (or simplest) solution is to use image():
library(raster)
# Raster
r = raster()
r[]= rnorm(ncell(r))
# Spatial points
x = c(-100, 0, 100)
y = c(100, 0, 100)
points = SpatialPoints(data.frame(x,y))
# plot
image(r)
plot(points, add=T, pch=16, cex=2)

Resources