country-labels on spplot() - r

I'd like to add name-labels for regions on an spplot().
Example:
load(url('http://gadm.org/data/rda/FRA_adm0.RData'))
FR <- gadm
FR <- spChFIDs(FR, paste("FR", rownames(FR), sep = "_"))
load(url('http://gadm.org/data/rda/CHE_adm0.RData'))
SW <- gadm
SW <- spChFIDs(SW, paste("SW", rownames(SW), sep = "_"))
load(url('http://gadm.org/data/rda/DEU_adm0.RData'))
GE <- gadm
GE <- spChFIDs(GE, paste("GE", rownames(GE), sep = "_"))
df <- rbind(FR, SW, GE)
## working
plot(df)
text(getSpPPolygonsLabptSlots(df), labels = c("FR", "SW", "GE"))
## not working
spplot(df[1-2,])
text((getSpPPolygonsLabptSlots(df), labels = c("FR", "SW"))
The second one probably doesn't work because of lattice!?
However, I need the spplot-functionality.
How would I get the labels on the plot?

Standard way of adding some text is using the function ltext of lattice, but the coordinates given there are always absolute. In essence, you can't really rescale the figure after adding the text. Eg :
data(meuse.grid)
gridded(meuse.grid)=~x+y
meuse.grid$g = factor(sample(letters[1:5], 3103, replace=TRUE),levels=letters[1:10])
meuse.grid$f = factor(sample(letters[6:10], 3103, replace=TRUE),levels=letters[1:10])
spplot(meuse.grid, c("f","g"))
ltext(100,200,"Horror")
Produces these figures (before and after scaling)
You can use a custom panel function, using the coordinates within each panel :
myPanel <- function(x,y,xx,yy,labels,...){
panel.xyplot(x,y,...)
ltext(xx,yy,labels)
}
xyplot(1:10 ~ 1:10,data=quakes,panel=myPanel,
xx=(1:5),yy=(1:5)+0.5,labels=letters[1:5])
(run it for yourself to see how it looks)
This trick you can use within the spplot function as well, although you really have to check whatever plotting function you use. In the help files on spplot you find the possible options (polygonsplot, gridplot and pointsplot), so you have to check whether any of them is doing what you want. Continuing with the gridplot above, this becomes :
myPanel <- function(x,y,z,subscripts,xx,yy,labels,...){
panel.gridplot(x,y,z,subscripts,...)
ltext(xx,yy,labels)
}
# I just chose some coordinates
spplot(meuse.grid, c("f","g"),panel=myPanel,xx=180000,yy=331000,label="Hooray")
which gives a rescalable result, where the text is added in each panel :

Thank you, Gavin Simpson!
I finally found a way.
In the hope it helps others in the future, I post my solution:
sp.label <- function(x, label) {
list("sp.text", coordinates(x), label)
}
ISO.sp.label <- function(x) {
sp.label(x, row.names(x["ISO"]))
}
make.ISO.sp.label <- function(x) {
do.call("list", ISO.sp.label(x))
}
spplot(df['ISO'], sp.layout = make.ISO.sp.label(df))

Related

Adjusting xaxis in plot.xts

I want to zoom into the chart. The chart from the code below use data from 2007 to 2019. I will like to look at the chart only from 2012 to 2015. Does anyone know how to do this?
I have tried with xlim = ("2012-01-01";"2015-01-01"), but that did not work.
library(quantmod)
getSymbols("AAPL")
plot.xts(AAPL[,6])
You have just to subset your xts-object to zoom it:
xts_data <- AAPL[ , 6]
xts_zoom <- xts_data['2012/2015']
plot.xts(xts_zoom)
The reason why setting xlim manually does not work is that the xlim values are calculated inside the plot.xts() itself. See, for example, the rows 123-134 of the plot.xts() source code:
if (cs$Env$observation.based) {
cs$Env$xycoords <- xy.coords(1:NROW(cs$Env$xdata[subset]))
cs$set_xlim(c(1, NROW(cs$Env$xdata[subset])))
cs$Env$xstep <- 1
}
else {
xycoords <- xy.coords(.index(cs$Env$xdata[cs$Env$xsubset]),
cs$Env$xdata[cs$Env$xsubset][, 1])
cs$Env$xycoords <- xycoords
cs$Env$xlim <- range(xycoords$x, na.rm = TRUE)
...
}
Another option is to use the built-in zoom tools of the quantmod package itself:
chartSeries(xts_data)
zoomChart('2012/2015')

R baseline package saving plots in a loop

I'm trying to optimize the parameters for baseline in the R baseline package by changing each parameters in a loop and comparing plots to determine which parameters give me the best baseline.
I currently have the code written so that the loop produces each plot, but I'm having trouble with getting the plot saved as the class of each object I'm creating is a baseline package-specific (which I'm suspecting is the problem here).
foo <- data.frame(Date=seq.Date(as.Date("1957-01-01"), by = "day",
length.out = ncol(milk$spectra)),
Visits=milk$spectra[1,],
Old_baseline_visits=milk$spectra[1,], row.names = NULL)
foo.t <- t(foo$Visits)
#the lines above were copied from https://stackoverflow.com/questions/37346967/r-packagebaseline-application-to-sample-dataset to make a reproducible dataset
df <- expand.grid(lambda=seq(1,10,1), p=seq(0.01,0.1,0.01))
baselinediff <- list()
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- plot(thisplot)
jpeg(file = paste(baselinediff[[i]], '.jpeg', sep = ''))
dev.off()
}
I know that I would be able to extract corrected spectra using baseline.als but I just want to save the plot images with the red baseline so that I can see how well the baselines are getting drawn. Any baseline users out there that can help?
I suggest you change your loop in the following way:
for(i in 1:nrow(df)){
thislambda <- df[i,]$lambda
thisp <- df[i,]$p
thisplot <- baseline(foo.t, lambda=thislambda, p=thisp, maxit=20, method='als')
print(paste0("lambda = ", thislambda))
print(paste0("p = ", thisp))
print(paste0("index = ", i))
baselinediff[[i]] <- thisplot
jpeg(file = paste('baseline', i, '.jpeg', sep = ''))
plot(baselinediff[[i]])
dev.off()
}
Note that this does not try to capture the already plotted element (thisplot) inside of the list. Instead, the plotting is done after you call the jpeg command. This solves your export issue. Another problem was the naming of the file. If you call baselinediff[[i]] inside of paste, you apparently end up with an error. So I switched it to a simpler name. To plot your resulting list, call:
lapply(baselinediff, plot)
If you are determined on storing the already plotted element, the capture.plotfunction from the imager package might be a good start.

I am trying to run mosaic for two multi-band images.Output saved as Single band

This is final output I got, I'm supposed to get the final output as a single file with two bands:
Following is the code which I am using:
A11 <-brick("E:/Official/PROJECTS/R_Progrm/1.tif") // to read multiband image
B11<-brick("E:/Official/PROJECTS/R_Progrm/3.tif") // To read multiband image
mos1 <- mosaic(A11,B11,fun=max,tolerance=0.5,
filename="Mosaic_new",overwrite=TRUE)
plot(mos1,main="Mosaic_new1")
writeRaster(x=mos1,file="E:/Official/PROJECTS/R_Progrm/M11.tif",options="INTERLEAVE=BAND",format="GTiff",datatype="FLT8S",overwrite=TRUE)
The plot that you have shown in your question, is showing both the bands of your output image. So, there should not be any problem with your code and its output. If the problem is related to visualizing all the bands as an RGB Image, then you have to modify the parameters of plot function that means you have to provide the band combination. For example:
plotRGB(a, r = 4, g = 3, b = 2, axes=TRUE, main="3 Band Color Composite Image")
box(col="white")
Also, you can try the code given below which is working fine for me, and I hope it will resolve your problem.
a <- stack("Path to first raster")
b <- stack("Path to second raster")
rast.list <- list(a,b)
rast.list$fun <- mean
rast.mosaic <- do.call(mosaic,rast.list)
plot(rast.mosaic)
writeRaster(rast.mosaic,"Output_Raster_Name",format="GTiff",overwrite=TRUE)
rm(list = ls())
gc()
memory.limit(size= 2000)
library(rgdal)
library(raster)
install.packages("gdalUtils")
library(gdalUtils)
library(sp)
setwd("E:/Official/PROJECTS/R_Progrm/MOs/")
list.files()
file1=file.path(getwd(), "", "1.tif")
gdal_setInstallation()
valid_install <- !is.null(getOption("gdalUtils_gdalPath"))
if(require(raster) && require(rgdal) && valid_install)
{
layer1 <- file.path(getwd(), "", "1.tif")
layer2 <- file.path(getwd(), "", "3.tif")
file_list=c(layer1,layer2)
mosaic_rasters(gdalfile=file_list,dst_dataset="E:/Official/PROJECTS/R_Progrm/MOs//test_mosaic.GTiff",separate=TRUE,of="GTiff",verbose=TRUE)
gdalinfo("test_mosaic.GTiff")
}

Use math symbols in panel titles for stratigraphic plot

I want to include math symbols in the panel titles for this stratigraphic plot:
library(analogue)
data(V12.122)
Depths <- as.numeric(rownames(V12.122))
names(V12.122)
(plt <- Stratiplot(Depths ~ O.univ + G.ruber + G.tenel + G.pacR,
data = V12.122,
type = c("h","l","g"),
zones = 400))
plt
For example, I want to have this text in place of "O.univ" etc.:
I used this code to make that text:
plot(1, type="n", axes=FALSE, ann=FALSE)
title(line = -1, main = expression(phantom()^14*C~years~BP))
title(line = -3, main = expression(delta^18*O))
title(line = -5, main = expression(paste("TP ", mu,"g l"^-1)))
title(line = -10, main = expression("very long title \n with \n line breaks"))
But if I try to update the colnames of the data frame passed to Stratiplot, the code is not parsed, and we do not get the correct text formatting:
V12.122 <- V12.122[, 1:4]
names(V12.122)[1] <- expression(phantom()^14*C~years~BP)
names(V12.122)[2] <- expression(delta^18*O)
names(V12.122)[3] <- expression(paste("TP ", mu,"g l"^-1))
(plt <- Stratiplot(Depths ~ .,
data = V12.122,
type = c("h","l","g"),
zones = 400))
plt
How can I get Stratiplot to parse the expressions in the colnames and format them correctly in the plot?
I've tried looking through str(plt) to see where the panel titles are stored, but no success:
text <- expression(phantom()^14*C~years~BP)
plt$condlevels$ind[1] <- text
names(plt$packet.sizes)[1] <- text
names(plt$par.settings$layout.widths$panel)[1] <- text
You can't actually do this in the current release of analogue; the function is doing too much messing around with data for the expressions to remain unevaluated prior to plotting. I could probably figure this out to allow expressions as the names of the data argument object, but it is easier to just allow users to pass a vector of labels that they want for the variables.
This is now implemented in the development version of the package on github, and I'll push this to CRAN early next week.
This change implements a new argument labelValues which takes a vector of labels for use in labelling the top axis. This can be a vector of expressions.
Here is an illustration of the usage:
library("analogue")
set.seed(1)
df <- setNames(data.frame(matrix(rnorm(200 * 3), ncol = 3)),
c("d13C", "d15N", "d18O"))
df <- transform(df, Age = 1:200)
exprs <- expression(delta^{13}*C, # label for 1st variable
delta^{15}*N, # label for 2nd variable
delta^{18}*O) # label for 3rd variable
Stratiplot(Age ~ ., data = df, labelValues = exprs, varTypes = "absolute", type = "h")
which produces
Note that this is just a first pass; I'm pretty sure I haven't accounted for any reordering that goes on with sort and svar etc. if they are used.
Never used lattice plots, but I thought a chance to learn something should be worth while. Took too long to figure out.
text <- "c( expression(phantom()^14*C~years~BP),expression(delta^18*O))"
strip = strip.custom(factor.levels=eval(parse(text=text)))
plt <- Stratiplot(Depths ~ .,
data = V12.122[, 1:4],
type = c("h","l","g"),
zones = 400,
strip = strip)
Hope this gets you started.

R spplot diagrams on the map

Hallo everyone can anybody help me to upgrade my code with possibility of insering additional data into my map. This is the code that draw me a map with intensity of migration, and I am trying to add ehtnic information of every region (many small pie charts).
to draw a map
con <- url("http://biogeo.ucdavis.edu/data/gadm2/R/UKR_adm1.RData")
print(load(con))
close(con)
name<-gadm$VARNAME_1
value<-c(4,2,5,2,1,2,4,2,2,4,1,1,1,4,3,3,1,1,3,1,2,4,5,3,4,2,1)
gadm$VARNAME_1<-as.factor(value)
col<- colorRampPalette(c('cadetblue4','cadetblue1','mediumseagreen','tan2','tomato3'))(260)
spplot(gadm, "VARNAME_1", main="Ukraine", scales = list(draw = TRUE), col.regions=col)
sp.label <- function(x, label) {
list("sp.text", coordinates(x), label)
}
NAME.sp.label <- function(x) {
sp.label(x, x$NAME_1)
}
draw.sp.label <- function(x) {
do.call("list", NAME.sp.label(x))
}
spplot(gadm, 'VARNAME_1', sp.layout = draw.sp.label(gadm), col.regions=col,
colorkey = list(labels = list( labels = c("Very low","Low", "Average",
"High","Very high"),
width = 1, cex = 1)))
and this is a part of df, that I am trying to add to that map as pie charts or bar charts, with every latitude (lat) and longitude (long) to locate mu bar or pie charts.
df<-data.frame(region=c('Kiev oblast', 'Donezk oblast'),
rus=c(45,35), ukr=c(65,76), mold=c(11,44),long=c(50.43,48),
lat=c(30.52, 37.82))
i found one example and another but... can't figure out how to use it in ma case.
Hope for your help, thank you.
only that solution i have discovered by now, but it doesn't upgrade my code(((
mapPies( df,nameX="lat", nameY="long", nameZs=c('rus','ukr','mold'),
xlim=c(30,33), ylim=c(44,53), symbolSize = 2)
perhaps this will help:
pieSP The function provide SpatialPolygonsDataFrame depending on few attributes, ready to use for plotGoogleMaps or spplot.
library(plotGoogleMaps)
data(meuse)
coordinates(meuse)<-~x+y
proj4string(meuse) <- CRS('+init=epsg:28992')
pies <- pieSP(meuse,zcol=c('zinc','lead','copper'), max.radius=120)
pies$pie <- rep(c('zinc','lead','copper'),155)
pies$pie2 <- rep(1:3,155)
spplot(pies, 'pie2')

Resources