These functions create interpolated surfaces out of data at individual
monitoring sites. This can be useful to 'fill in the gaps' to estimate
pollution concentrations where no monitoring is occurring, or better
identify geographical patterns in pollution data. krigingMap() creates a
smooth spatially interpolated surface using either inverse distance
weighting or point kriging. voronoiMap() creates a surface of 'closest
observation' polygons. The kriging formula is currently always pollutant ~ 1; krigingMap() does not currently support more complex models.
When type is used, each type level is summarised and interpolated
separately, but all levels share the same colour scale so that they can
be compared.
Usage
krigingMap(
data,
pollutant = NULL,
statistic = "mean",
percentile = 95,
newdata = NULL,
method = c("idw", "kriging"),
breaks = NULL,
labels = NULL,
limits = NULL,
latitude = NULL,
longitude = NULL,
crs = 4326,
type = NULL,
popup = NULL,
label = NULL,
provider = "OpenStreetMap",
cols = "turbo",
alpha = 0.8,
show.markers = TRUE,
marker.border = "white",
legend = TRUE,
legend.position = NULL,
legend.title = NULL,
legend.title.autotext = TRUE,
control.collapsed = FALSE,
control.position = "topright",
control.autotext = TRUE,
static = FALSE,
static.nrow = NULL,
api_key = NULL,
vgm = gstat::vgm(psill = 1, model = "Exp", range = 50, nugget = 1),
args.idw = list(debug.level = 0),
args.variogram = list(),
args.fit.variogram = list(),
args.krige = list(debug.level = 0),
...
)
voronoiMap(
data,
pollutant = NULL,
statistic = "mean",
percentile = 95,
newdata = NULL,
breaks = NULL,
labels = NULL,
limits = NULL,
latitude = NULL,
longitude = NULL,
crs = 4326,
type = NULL,
popup = NULL,
label = NULL,
provider = "OpenStreetMap",
cols = "turbo",
alpha = 0.8,
show.markers = TRUE,
marker.border = "white",
voronoi.border = "white",
legend = TRUE,
legend.position = NULL,
legend.title = NULL,
legend.title.autotext = TRUE,
control.collapsed = FALSE,
control.position = "topright",
control.autotext = TRUE,
static = FALSE,
static.nrow = NULL,
api_key = NULL,
args.voronoi = list(),
...
)Arguments
- data
Input data table with pollutant and geo-spatial information.
required | scope: dynamic & static
A data frame. The data frame must contain at least one numeric column to interpolate, plus a decimal latitude and longitude (or X/Y coordinate used in conjunction with
crs).- pollutant
Pollutant name.
required | scope: dynamic & static
The column name of the pollutant to plot. Multiple
pollutantsare prohibited by this function.- statistic
Statistic for aggregating pollutant data.
default:
"mean"| scope: dynamic & staticPollutant data will be aggregated by latitude & longitude;
statisticcontrols how this is achieved. Possible statistics include:"mean": the arithmetic mean (usingbase::mean())"median": the median (middle) value (usingstats::median())"max": the maximum value (usingmax())"min": the minimum value (usingmin())"sd": the standard deviation (usingstats::sd())"percentile": a percentile value, defined using thepercentileargument (usingstats::quantile())
To show this value in marker popups or labels, include
pollutantinpopuporlabel(e.g.,popup = c("site", "nox")).- percentile
The percentile when `statistic = "percentile"
default:
95| scope: dynamic & staticThe percentile level used when
statistic = "percentile". The default is95, representing 95%. Should be between0and100.- newdata
A spatial dataset of prediction locations.
default:
NULL| scope: dynamic & staticBy default, a bounding box of all latitudes and longitudes are used for prediction, but this is often not useful or aesthetically pleasing.
newdatashould be a spatial data frame (constructed withsf::st_as_sf()). This may be a country or authority boundary relevant to thedatainput.- method
Spatial interpolation method.
default:
"idw"| scope: dynamic & staticThe spatial interpolation method to use for
krigingMap()."idw"uses inverse distance weighting (IDW) which is simpler and faster."kriging"uses full point kriging which is typically more accurate, but is also more complex and computationally intensive.- labels, breaks
Discretise the map color scale.
default:
NULL| scope: dynamic & staticBy default, a continuous colour scale is used. If
breaksare provided, the colour scale will be discretised usingcut().labelscan also be provided to customise how each factor level is labelled.If the data extend beyond
breaks, the outermost breaks are expanded to cover them so that no sites are left uncoloured. For example,breaks = c(50, 100, 150)would becomec(25, 100, 200)for data ranging from 25 to 200.- limits
Specifier for the plot colour scale bounds.
default:
NULL| scope: dynamic & staticA numeric vector in the form
c(lower, upper)used to define the colour scale. For example,limits = c(0, 100)would force the plot limits to span 0-100. IfNULL, appropriate limits will be selected based on the range indata[[pollutant]]. Values outside oflimitsare given the colour of the nearest limit.- latitude, longitude
The decimal latitude(Y)/longitude(X).
default:
NULL| scope: dynamic & staticColumn names representing the decimal latitude and longitude (or other Y/X coordinate if using a different
crs). If not provided, will be automatically inferred from data by looking for a column named "lat"/"latitude" or "lon"/"lng"/"long"/"longitude" (case-insensitively).- crs
The coordinate reference system (CRS).
default:
4326| scope: dynamic & staticThe coordinate reference system (CRS) of the data, passed to
sf::st_crs(). By default this is EPSG:4326, the CRS associated with the commonly used latitude and longitude coordinates. Different coordinate systems can be specified usingcrs(e.g.,crs = 27700for the British National Grid). Note that non-lat/lng coordinate systems will be re-projected to EPSG:4326 for plotting on the map.- type
A method to condition the
datafor separate plotting.default:
NULL| scope: dynamic & staticUsed for splitting the input data into different groups, passed to the
typeargument ofopenair::cutData(). Whentypeis specified:Dynamic: The different data splits can be toggled between using a "layer control" menu.
Static: The data splits will each appear in a different panel.
typecannot be used if multiplepollutantcolumns have been provided.- popup
Content for marker popups on dynamic maps.
default:
NULL| scope: dynamicColumns to be used as the HTML content for site marker popups on dynamic maps. Popups may be useful to show information about the individual sites (e.g., site names, codes, types, etc.). If a vector of column names are provided they are passed to
buildPopup()using its default values.The
pollutantcolumn shows the sitestatistic(i.e., what the markers are coloured by), labelled as such (e.g., "NO2 (max)"). Any other numeric columns have many values at each site, so are averaged and labelled "(mean)". Names given topopup(e.g.,c("Site NOx" = "nox")) are used instead of these labels.- label
Content for marker hover-over on dynamic maps.
default:
NULL| scope: dynamicColumn to be used as the HTML content for hover-over labels. Labels are useful for the same reasons as popups, though are typically shorter. The
pollutantcolumn shows the sitestatistic, and other numeric columns are averaged at each site.- provider
The basemap(s) to be used.
default:
"OpenStreetMap"| scope: dynamic & staticThe base map(s) to be used for the map. If not provided, will default to
"OpenStreetMap"/"osm"for both dynamic and static maps.Dynamic: Any number of leaflet::providers. See http://leaflet-extras.github.io/leaflet-providers/preview/ for a list of all base maps that can be used. If multiple base maps are provided, they can be toggled between using a "layer control" interface. By default, the interface will use the provider names as labels, but users can define their own using a named vector (e.g.,
c("Default" = "OpenStreetMap", "Satellite" = "Esri.WorldImagery"))Static: One of the options listed in
rosm::osm.types()(for example,"osm","cartodark","cartolight", etc.).
There is some overlap in static and dynamic providers. For example,
{ggspatial}uses "osm" to specify "OpenStreetMap". When static providers are provided to dynamic maps or vice versa,{openairmaps}will attempt to substitute the correct provider string.- cols
Colours to use for plotting.
default:
"turbo"| scope: dynamic & staticThe colours used for plotting, passed to
openair::openColours(). The default,"turbo", is a rainbow palette with relatively perceptually uniform colours.- alpha
Transparency value for interpolated surface.
default:
0.8| scope: dynamic & staticA value between 0 (fully transparent) and 1 (fully opaque).
- show.markers
Show original monitoring site markers?
default:
TRUE| scope: dynamic & staticWhen
TRUE, the coordinates in the inputdatawill be shown as coloured markers. Anypopuporlabelis attached to these markers, so neither is shown whenshow.markers = FALSE.- marker.border, voronoi.border
Border colour to use for markers and voronoi tiles.
default:
"white"| scope: dynamic & staticAny valid HTML colour (e.g., a hex code). Use
NAfor no border.- legend
Draw a legend?
default:
TRUE| scope: dynamic & staticWhen
TRUE, a legend will appear on the map identifying the colour scale.- legend.position
Position of the shared legend.
default:
NULL| scope: dynamic & staticWhen
legend = TRUE, where should the legend be placed?Dynamic: One of "topright", "topleft", "bottomleft" or "bottomright". Passed to the
positionargument ofleaflet::addLegend().Static: One of "top", "right", "bottom" or "left". Passed to the
legend.positionargument ofggplot2::theme().
- legend.title
Title of the legend.
default:
NULL| scope: dynamic & staticBy default, when
legend.title = NULL, the function will attempt to provide a sensible legend title.legend.titleallows users to overwrite this - for example, to include units or other contextual information. For dynamic maps, users may wish to use HTML tags to format the title.- legend.title.autotext
Automatically format the title of the legend?
default:
TRUE| scope: dynamic & staticWhen
legend.title.autotext = TRUE,legend.titlewill be first run throughquickTextHTML()(dynamic) oropenair::quickText()(static).- control.collapsed
Show the layer control as a collapsed?
default:
FALSE| scope: dynamicFor dynamic maps, should the "layer control" interface be collapsed? If
TRUE, users will have to hover over an icon to view the options.- control.position
Position of the layer control menu
default:
"topright"| scope: dynamicWhen
type != NULL, or multiple pollutants are specified, where should the "layer control" interface be placed? One of "topleft", "topright", "bottomleft" or "bottomright". Passed to thepositionargument ofleaflet::addLayersControl().- control.autotext
Automatically format the content of the layer control menu?
default:
TRUE| scope: dynamicWhen
control.autotext = TRUE, the content of the "layer control" interface will be first run throughquickTextHTML().- static
Produce a static map?
default:
FALSEThis controls whether a dynamic or static map is produced. The former is the default and is broadly more useful, but the latter may be preferable for DOCX or PDF outputs (e.g., academic papers).
- static.nrow
Number of rows in a static map.
default:
NULL| scope: staticControls the number of rows of panels on a static map when multiple
pollutants ortypeare specified; passed to thenrowargument ofggplot2::facet_wrap(). The default,NULL, results in a roughly square grid of panels.- api_key
API key for certain 'static' base map providers.
default:
NULL| scope: staticPassed to the
api_keyargument ofggspatial::annotation_map_tile(). Needed for certainproviders(e.g.,"cartolight").- vgm
A variogram model
default:
gstat::vgm(psill = 1, model = "Exp", range = 50, nugget = 1)| scope: dynamic & staticThe variogram model to use when
method = "kriging". Must be the output ofgstat::vgm(). As the data are in latitude and longitude,{gstat}measures distances (e.g., therange) in kilometres.- args.idw, args.variogram, args.fit.variogram, args.krige
Extra arguments to pass to spatial interpolation functions for
krigingMap().scope: dynamic & static
Extra arguments passed to
gstat::idw(),gstat::variogram(),gstat::fit.variogram(), andgstat::krige().gstat::idw()andgstat::krige()are silenced by default (debug.level = 0), but this can be overridden (e.g.,args.idw = list(debug.level = 1)).- ...
Arguments passed on to
openair::cutDatanamesBy default, the columns created by
cutData()are named after theirtypeoption. Specifyingnamesdefines other names for the columns, which map onto thetypeoptions in the same order they are given. The length ofnamesshould therefore be equal to the length oftype.suffixIf
namesis not specified,suffixwill be appended to any added columns that would otherwise overwrite existing columns. For example,cutData(mydata, "nox", suffix = "_cuts")would append anox_cutscolumn rather than overwritingnox.hemisphereCan be
"northern"or"southern", used to split data into seasons.n.levelsNumber of quantiles to split numeric data into.
wd.resThe number of wind direction bins; one of
4(N/E/S/W),8(N/NE/E/SE/etc., the default),16(N/NNE/NE/ENE/etc.) or32(N/NbE/NNE/NEbN/etc.).start.dayWhat day of the week should the
type = "weekday"start on? The user can change the start day by supplying an integer between 0 and 6. Sunday = 0, Monday = 1, ... For example to start the weekday plots on a Saturday, choosestart.day = 6.start.seasonWhat order should the season be. By default, the order is spring, summer, autumn, winter.
start.season = "winter"would plot winter first.is.axisA logical (
TRUE/FALSE), used to request shortened cut labels for axes.local.tzUsed for identifying whether a date has daylight savings time (DST) applied or not. Examples include
local.tz = "Europe/London",local.tz = "America/New_York", i.e., time zones that assume DST. https://en.wikipedia.org/wiki/List_of_zoneinfo_time_zones shows time zones that should be valid for most systems. It is important that the original data are in GMT (UTC) or a fixed offset from GMT.latitude,longitudeThe decimal latitude and longitudes used when
type = "daylight". Note that locations west of Greenwich have negative longitudes.dropHow to handle empty factor levels. One of:
"default": Sensible defaults selected on a case-by-case basis for differenttypeoptions."empty": Drop all empty factor levels."none": Retain all empty factor levels, where possible. For example, fortype = "hour", all factor levels from0and23will be represented."outside": Retain empty factor levels within the range of the data. For example, fortype = "hour"when the data only contains data for 1 AM and 5 AM, the factor levels,1,2,3,4and5will be retained.
Some of these options only apply to certain
typeoptions. For example, fortype = "year","outside"is equivalent to"none"as there is no fixed range of years to use in the"none"case.
- args.voronoi
Extra arguments to pass to spatial interpolation functions for
voronoiMap().scope: dynamic & static
Extra arguments passed to
terra::voronoi(), with the exception ofxwhich is dealt with byvoronoiMap().
Value
Either:
Dynamic: A leaflet object
Static: A
ggplot2object usingggplot2::coord_sf()coordinates with aggspatialbasemap
Customisation of static maps using ggplot2
As all static plots functions are ggplot2 figures, further customisation
is possible using functions such as ggplot2::theme(), ggplot2::guides()
and ggplot2::labs().
Subscripting pollutants (e.g., the "x" in "NOx") is achieved using the
ggtext package. Therefore if you choose to override the
plot theme, it is recommended to use [ggplot2::theme()] and
[ggtext::element_markdown()] to define the strip.text parameter.
Legends can be removed using ggplot2::theme(legend.position = "none"), or
further customised using ggplot2::guides() and either color = ggplot2::guide_colourbar() for continuous legends or color = ggplot2::guide_legend() for discrete legends.
The extent of a map can be adjusted using the xlim and ylim arguments
of ggplot2::coord_sf().
Examples
if (FALSE) { # \dontrun{
# import ozone DAQI
daqi <-
openair::importUKAQ(
pollutant = "o3",
year = 2020,
source = "aurn",
data_type = "daqi",
meta = TRUE
)
# get a UK shapefile
uk <- rnaturalearth::ne_countries(scale = 10, country = "united kingdom")
# create spatially interpolated map
voronoiMap(
daqi,
pollutant = "poll_index",
newdata = uk,
statistic = "max",
breaks = seq(0.5, 10.5, 1),
labels = as.character(1:10),
legend.title = "Max O3 DAQI",
cols = "daqi"
)
krigingMap(
daqi,
pollutant = "poll_index",
newdata = uk,
statistic = "max",
legend.title = "Max O3 DAQI",
cols = openair::openColours("daqi", n = 10),
limits = c(1, 10)
)
} # }
