Skip to content

Commit

Permalink
add levelplot2 for spatialGrid
Browse files Browse the repository at this point in the history
  • Loading branch information
kongdd committed Oct 23, 2019
1 parent 347bf6f commit 0b82d9c
Show file tree
Hide file tree
Showing 23 changed files with 834 additions and 222 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ inst/doc

tests/testthat/*.svg
tests/testthat/*.tif

*.svg
7 changes: 5 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Description: Awesome functions in R.
License: GPL-3
Encoding: UTF-8
LazyData: TRUE
Depends:
R (>= 3.1)
LinkingTo:
Rcpp
import:
Expand All @@ -29,7 +31,7 @@ Imports:
methods,
parallel,
doParallel,
foreach,
foreach, iterators,
plyr,
Cairo,
Rcpp,
Expand All @@ -40,7 +42,8 @@ Imports:
devtools,
IRdisplay,
RColorBrewer,
sp,
sp, maptools,
rgeos,
boot
Suggests:
testthat (>= 2.1.0),
Expand Down
25 changes: 25 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ export(addin_insertReturn)
export(apply_3d)
export(apply_col)
export(apply_row)
export(area.spatial)
export(array_3dTo2d)
export(box_qtl)
export(check_dir)
export(chunk)
export(clamp)
export(clamp_min)
export(colorkey_pos)
export(contain)
export(convertTri)
Expand Down Expand Up @@ -49,6 +52,7 @@ export(key_gf)
export(key_label)
export(key_triangle)
export(killCluster)
export(levelplot2)
export(listk)
export(load_all2)
export(makeVIDEO)
Expand Down Expand Up @@ -133,26 +137,38 @@ importFrom(foreach,"%do%")
importFrom(foreach,foreach)
importFrom(ggplot2,ggplot_gtable)
importFrom(grDevices,cairo_pdf)
importFrom(grDevices,colorRampPalette)
importFrom(grDevices,dev.off)
importFrom(grDevices,svg)
importFrom(grDevices,tiff)
importFrom(grDevices,windowsFont)
importFrom(grDevices,windowsFonts)
importFrom(grDevices,xy.coords)
importFrom(graphics,abline)
importFrom(graphics,grid)
importFrom(graphics,legend)
importFrom(graphics,par)
importFrom(graphics,plot)
importFrom(graphics,rect)
importFrom(grid,frameGrob)
importFrom(grid,gpar)
importFrom(grid,grid.draw)
importFrom(grid,grid.grabExpr)
importFrom(grid,grid.layout)
importFrom(grid,grid.newpage)
importFrom(grid,grid.segments)
importFrom(grid,grobTree)
importFrom(grid,nullGrob)
importFrom(grid,placeGrob)
importFrom(grid,polygonGrob)
importFrom(grid,popViewport)
importFrom(grid,pushViewport)
importFrom(grid,rasterGrob)
importFrom(grid,rectGrob)
importFrom(grid,segmentsGrob)
importFrom(grid,textGrob)
importFrom(grid,viewport)
importFrom(iterators,icount)
importFrom(jsonlite,fromJSON)
importFrom(jsonlite,read_json)
importFrom(jsonlite,write_json)
Expand All @@ -174,6 +190,8 @@ importFrom(matrixStats,colSds)
importFrom(matrixStats,rowMaxs)
importFrom(matrixStats,rowMeans2)
importFrom(matrixStats,rowMins)
importFrom(matrixStats,weightedMedian)
importFrom(matrixStats,weightedSd)
importFrom(methods,as)
importFrom(openxlsx,read.xlsx)
importFrom(parallel,makeCluster)
Expand All @@ -188,9 +206,14 @@ importFrom(reshape2,melt)
importFrom(rstudioapi,getActiveDocumentContext)
importFrom(rstudioapi,getSourceEditorContext)
importFrom(rstudioapi,modifyRange)
importFrom(sp,coordinates)
importFrom(sp,panel.gridplot)
importFrom(sp,panel.polygonsplot)
importFrom(sp,sppanel)
importFrom(sp,spplot)
importFrom(stats,acf)
importFrom(stats,as.formula)
importFrom(stats,density)
importFrom(stats,lm)
importFrom(stats,median)
importFrom(stats,na.omit)
Expand All @@ -199,7 +222,9 @@ importFrom(stats,qnorm)
importFrom(stats,quantile)
importFrom(stats,setNames)
importFrom(stringr,str_extract)
importFrom(utils,modifyList)
importFrom(utils,object.size)
importFrom(utils,str)
importFrom(utils,write.table)
importFrom(xml2,read_xml)
importFrom(xml2,xml_find_all)
Expand Down
29 changes: 25 additions & 4 deletions R/Ipaper-package.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,13 @@
#' @importFrom data.table data.table
#' @importFrom graphics rect plot
#' @importFrom grid textGrob gpar grid.newpage
#' @importFrom grDevices cairo_pdf dev.off svg tiff
#' @importFrom grDevices cairo_pdf dev.off svg tiff colorRampPalette xy.coords
#' @importFrom stats quantile setNames
#' @importFrom utils object.size
#' @importFrom graphics abline grid legend
#' @importFrom stats acf as.formula lm median na.omit pnorm qnorm
#' @importFrom utils write.table
#' @importFrom graphics abline grid legend par
#' @importFrom stats acf as.formula lm median na.omit pnorm qnorm density
#' @importFrom utils write.table modifyList str
#'
#' @import magrittr plyr
#'
#' @keywords internal
Expand All @@ -33,6 +34,7 @@
NULL


#' @importFrom grDevices windowsFonts windowsFont
.onLoad <- function(libname, pkgname) {
# suppressMessages
# suppressWarnings
Expand All @@ -41,5 +43,24 @@ NULL
# library(lattice)
library(devtools)
})

OS.type = .Platform$OS.type
if (OS.type == 'windows') {

grDevices::windowsFonts(
Times = grDevices::windowsFont("Times New Roman"),
Arial = grDevices::windowsFont("Arial"),
YH = grDevices::windowsFont("Microsoft Yahei"),
whit = grDevices::windowsFont("Whitney-Book")
)
} else if (OS.type == 'unix'){
Cairo::CairoFonts(
regular="Times New Roman:style=Regular",
bold="Times New Roman:style=Bold",
italic="Times New Roman:style=Oblique",
bolditalic="Times New Roman:style=BoldOblique"
)
}

invisible()
}
29 changes: 29 additions & 0 deletions R/clamp.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
#' clamp
#'
#' clamp values in the range of `lims`
#'
#' @param x Numeric vector
#' @param lims limits
#' @param fill.na If true, values of lims are set to NA; else, values are just
#' constrained in the range of `lims`.
#'
#' @examples
#' clamp(1:10, lims = c(4, 7), fill.na = TRUE)
#' @export
clamp <- function(x, lims = c(0, 1), fill.na = FALSE){
if (fill.na) {
x[x < lims[1]] <- NA_real_
x[x > lims[2]] <- NA_real_
} else {
x[x < lims[1]] <- lims[1]
x[x > lims[2]] <- lims[2]
}
x
}

#' @rdname clamp
#' @export
clamp_min <- function(x, value = 0){
x[x < value] <- value
x
}
9 changes: 7 additions & 2 deletions R/coord.polygon.R
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,13 @@
#'
#' @param x Polygons class
#' @export
coord.polygon <- function(x){
map(x@Polygons, ~.x@coords) %>% do.call(rbind, .)
coord.polygon <- function(x){
res = list()
xs = x@Polygons
for(i in seq_along(xs)) {
res[[i]] = xs[[i]]@coords
}
do.call(rbind, res)
}

#' coord.polygons
Expand Down
130 changes: 130 additions & 0 deletions R/levelplot2.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,130 @@
#' Plot methods for spatial data with attributes
#'
#' Lattice (trellis) plot methods for spatial data with attributes
#'
#' @inheritParams lattice::levelplot
#' @inheritParams sp::spplot
#'
#' @param formula a formula of the form z ~ x * y | g1 * g2 * ..., where z is a
#' numeric response, and x, y are numeric values evaluated on a rectangular grid.
#' g1, g2, ... are optional conditional variables, and must be either factors or
#' shingles if present.
#' @param df data.table object, with columns e.g. lon, lat, and others
#' @param df.mask NULL or same length data.table as df, with the columns of `mask`
#' and same group variabes as `df`. Mask is used to distinguish significant pixels.
#'
#' @param NO_begin beginning NO of the first panel
#'
#' @example man/examples/ex-spplot_grid.R
#'
#' @seealso [spplot_grid()], [sp::spplot()], [lattice::levelplot()]
#'
#' @importFrom matrixStats weightedMedian weightedSd
#' @importFrom sp spplot coordinates
#' @importFrom grid frameGrob placeGrob rectGrob segmentsGrob polygonGrob
#' @importFrom lattice panel.number panel.segments panel.points panel.arrows
#' @export
levelplot2 <- function(
formula,
df,
SpatialPixel,
df.mask = NULL,
# grid, zcols,
brks, colors, col.rev = FALSE,
toFactor = FALSE,
sub.hist = TRUE,
grob = NULL, bbox = c(0, 0.5, 0.5, 1),
xlim = c(73.5049, 104.9725), ylim = c(25.99376, 40.12632),
panel.title = NULL,
unit = "",
unit.adj = 0.3,
pars = list(title = list(x=77, y=39, cex=1.5),
hist = list(origin.x=77, origin.y=28, A=15, by = 0.4)),
stat = list(show = FALSE, name="RC", loc = c(81.5, 26.5), digit = 1, include.sd = FALSE),
area.weighted = FALSE,
legend.space = "right",
layout = NULL,
colorkey = TRUE,
interpolate = TRUE,
lgd.title = NULL,
sp.layout = NULL,
NO_begin = 1,
par.settings = opt_trellis_default,
par.settings2 = list(axis.line = list(col = "white")),
...)
{
info.formula = parse.formula(formula)
value.var = info.formula$value.var
groups = info.formula$groups

npixel = nrow(SpatialPixel)
par.settings <- modifyList(par.settings, par.settings2)

list.mask = if (!is.null(df.mask)) {
dlply(df.mask, groups, function(d) d$mask)
} else NULL

# statistic mean value
data.stat <-
if (stat$show && !is.null(stat$loc)) {
area = area.spatial(SpatialPixel, area.weighted)
# need to debug for two variables group
labels = dlply(df, groups, function(d) spatial_meansd(d[[value.var]], area, stat, unit))
list(loc = stat$loc, label = labels)
} else NULL

if (missing(colors)){ colors <- c("red", "grey80", "blue4") }
if (missing(brks)) {
vals <- df[[value.var]]
range <- quantile(vals, c(0.05, 0.95), na.rm = TRUE)
vals %<>% clamp(range)
brks <- pretty(vals, n = 10) %>% c(-Inf, ., Inf)
cols <- get_break_colors(colors, brks)
} else {
cols <- get_break_colors(colors, brks)
if (toFactor) df[[value.var]] %<>% cut(brks) # cut into factor
levels <- cut(1, brks) %>% levels()
}
if (col.rev) cols %<>% rev()

class <- class(SpatialPixel)
data <- coordinates(SpatialPixel) %>% as.data.table() %>% cbind(df)
params <- list(
formula, data,
list.mask = list.mask,
SpatialPixel = SpatialPixel,
...,
col.regions = cols,
# panel.titles = zcols,
panel.titles_full = panel.title,
panel = panel.spatial,
NO_begin = NO_begin,
sub.hist = sub.hist,
brks = brks,
xlim = xlim, ylim = ylim,
strip = FALSE, as.table = TRUE,
sp.layout = sp.layout,
layout = layout,
scales = list(draw = FALSE),
xlab = NULL, ylab = NULL,
# drop.unused.levels = FALSE,
interpolate = interpolate,
par.settings = par.settings,
grob = grob, bbox = bbox,
pars = pars,
data.stat = data.stat,
class = class
)
is_factor <- is.factor(df[[value.var]])
if (!is_factor) params$at <- brks

if (colorkey) {
params$colorkey <- get_colorkey(brks, legend.space, lgd.title, is_factor)$colorkey
params$colorkey$unit = unit
params$colorkey$unit.adj = unit.adj
} else {
params$colorkey <- FALSE
}
# browser()
do.call(levelplot, params)
}
Loading

0 comments on commit 0b82d9c

Please sign in to comment.