These functions provide convenient ggplot2 layers for drawing gradient fields
by computing the gradient of a scalar field. A user-defined function (fun)
specifies the behavior of the scalar field by taking a numeric vector of
length 2 (representing \((x, y)\)) and returning a single numeric value.
The underlying StatStreamField computes the gradient via numerical
differentiation (using numDeriv::grad()) and GeomStream renders the
resulting vectors.
Usage
geom_gradient_field(
mapping = NULL,
data = NULL,
stat = StatStreamField,
position = "identity",
...,
na.rm = FALSE,
show.legend = TRUE,
inherit.aes = FALSE,
fun,
xlim = NULL,
ylim = NULL,
n = 11,
max_it = 1000,
method = "rk4",
T = NULL,
L = NULL,
center = TRUE,
type = "vector",
normalize = TRUE,
tail_point = FALSE,
eval_point = FALSE,
grid = NULL,
domain = NULL,
lineend = "butt",
linejoin = "round",
linemitre = 10,
arrow = grid::arrow(angle = 30, length = grid::unit(0.02, "npc"), type = "closed")
)
stat_gradient_field(
mapping = NULL,
data = NULL,
geom = GeomStream,
position = "identity",
...,
na.rm = FALSE,
show.legend = TRUE,
inherit.aes = FALSE,
fun,
xlim = NULL,
ylim = NULL,
n = 11,
max_it = 1000,
method = "rk4",
T = NULL,
L = NULL,
center = TRUE,
type = "vector",
normalize = TRUE,
tail_point = FALSE,
eval_point = FALSE,
grid = NULL,
domain = NULL,
lineend = "butt",
linejoin = "round",
linemitre = 10,
arrow = grid::arrow(angle = 30, length = grid::unit(0.02, "npc"), type = "closed")
)
geom_gradient_field2(
mapping = NULL,
data = NULL,
stat = StatStreamField,
position = "identity",
...,
na.rm = FALSE,
show.legend = TRUE,
inherit.aes = FALSE,
fun,
xlim = NULL,
ylim = NULL,
n = 11,
max_it = 1000,
method = "rk4",
T = NULL,
L = NULL,
center = FALSE,
type = "stream",
normalize = TRUE,
tail_point = TRUE,
eval_point = FALSE,
grid = NULL,
domain = NULL,
lineend = "butt",
linejoin = "round",
linemitre = 10,
arrow = NULL
)
stat_gradient_field2(
mapping = NULL,
data = NULL,
geom = GeomStream,
position = "identity",
...,
na.rm = FALSE,
show.legend = TRUE,
inherit.aes = FALSE,
fun,
xlim = NULL,
ylim = NULL,
n = 11,
max_it = 1000,
method = "rk4",
T = NULL,
L = NULL,
center = FALSE,
type = "stream",
normalize = TRUE,
tail_point = TRUE,
eval_point = FALSE,
grid = NULL,
domain = NULL,
lineend = "butt",
linejoin = "round",
linemitre = 10,
arrow = NULL
)Arguments
- mapping
A set of aesthetic mappings created by
ggplot2::aes(). Additional aesthetics such ascolor,size,linetype, andalphacan be defined. In geom_gradient_field the default mapping iscolor = after_stat(norm)for vectors andcolor = after_stat(avg_spd)for streams, whereas in geom_gradient_field2 withtype = "vector"it includeslength = after_stat(norm).- data
A data frame containing the input data.
- stat
The statistical transformation to use on the data for this layer. Defaults to StatStreamField.
- position
Position adjustment, either as a string or the result of a position adjustment function.
- ...
Other arguments passed on to
grid::layer().- na.rm
Logical. If
FALSE(the default), missing values are removed with a warning.- show.legend
Logical. Should this layer be included in the legends?
- inherit.aes
Logical. If
FALSE, overrides the default aesthetics rather than combining with them.- fun
A function that defines the scalar field. It should take a numeric vector of length 2 (representing \((x, y)\)) and return a single numeric value. (Required)
- xlim
Numeric vector of length two. Specifies the limits of the x-axis domain. Defaults to
c(-1, 1).- ylim
Numeric vector of length two. Specifies the limits of the y-axis domain. Defaults to
c(-1, 1).- n
Integer. Grid resolution specifying the number of seed points along each axis. Higher values produce a denser gradient field. Defaults to
11.- max_it
Integer. Maximum number of integration steps allowed when computing the gradient stream. Defaults to
1000.- method
Character. Integration method.
"rk4"(Runge-Kutta 4, the default) and"euler"(Euler's method) step through the field in equal shares of the arc lengthLor, when streams are run to a timeT, of that time. A step is shortened where the field turns or changes speed sharply, so a stream that runs into a sink or a singularity (such as a point charge) stops there, short ofL, while a stream that meets a jump in the field (for example one defined withsign()orifelse()) carries on across it, unless the field on the far side points back. A stream that reaches a line the field converges on from both sides stops there; the exact solution would slide along the line. Sinks, singularities and jumps are told apart by how sharply the field turns and changes speed, so a field built to sit on those thresholds can be misjudged."lsoda"uses the adaptive solver fromdeSolve::ode(), stopping each stream when its arc length reachesL; it was the integrator in ggvfields 1.0.1.geom_stream_smooth()andgeom_gradient_smooth()always use"rk4".- T
Numeric. Used only with
normalize = FALSE. Each stream is run for timeTandLis ignored; withcenter = TRUEit runs forTforward andTbackward from the seed. Vectors (type = "vector") are always drawn asfun(x, y)scaled by a time of 1. Defaults toNULL.- L
Numeric. The length of each vector or stream; with
normalize = FALSEand noT, streams are grown toLand cut back to the time of the fastest one (seegeom_stream_field()). Defaults toNULL, which uses 85% of the spacing of the grid.- center
Logical. If
TRUE, centers the seed points so that the original (x, y) becomes the midpoint.- type
Character. Specifies the type of field to compute: use
"stream"to generate integrated streamlines or"vector"for individual vector segments. Defaults to"vector"ingeom_gradient_field()andstat_gradient_field(), and to"stream"ingeom_gradient_field2()andstat_gradient_field2().- normalize
Logical. If
TRUE(the default), every vector or stream has the same lengthL. IfFALSE, lengths show the size of the gradient; seegeom_stream_field()for how streams are then run.- tail_point
Logical. If
TRUE, a point is drawn at the tail of each gradient vector.- eval_point
Logical. If
TRUE, a point is drawn at the evaluation point where the gradient was computed. Defaults toFALSE.- grid
A data frame containing precomputed grid points for seed placement. If
NULL(default), a regular Cartesian grid is generated based onxlim,ylim, andn. For streams,grid = "even"places evenly spaced streamlines instead (Jobard and Lefer, 1997): each stream is grown in both directions until it comes within half a grid spacing of another stream, reaches a sink or leaves the plot, and new streams are started a grid spacing to either side of earlier ones, so the streams fill the plot about one grid spacing apart.L,Tandnormalizeare not used then; increasenfor denser streams.- domain
A function that restricts the field to a region, or
NULL(the default) for the whole rectanglexlimbyylim. It is called likefun, with a pointc(x, y), and returnsTRUEfor points in the region. Seeds outside the region are dropped, and the field is taken to be undefined outside it, so streams stop at its boundary. Use it, for example, whenfunis only defined on part of the plot.- lineend
Line end style (round, butt, square).
- linejoin
Line join style (round, mitre, bevel).
- linemitre
Line mitre limit (number greater than 1).
- arrow
A
grid::arrow()specification to add arrowheads to the gradient vectors. In geom_gradient_field, the default is a closed arrow with a 30° angle and length0.02npc; ingeom_gradient_field2(), the default isNULL.- geom
The geometric object used to render the streamline (only used in
stat_stream(); defaults to GeomStream).
Value
A ggplot2 layer that computes and plots a gradient field by numerically differentiating a scalar field.
Details
Two variants are provided:
geom_gradient_field() maps color to the size of the gradient:
color = after_stat(norm)for vectors (the default) andcolor = after_stat(avg_spd)for streams.geom_gradient_field2() leaves
colorunmapped and marks each seed point with a dot. Withtype = "vector"it setslength = after_stat(norm), so vectors are scaled by the size of the gradient, likegeom_vector_field2(). Streams (the default) ignorelength, so they get no default mapping, likegeom_stream_field2().
Aesthetics
geom_gradient_field() and geom_gradient_field2()
understand the following aesthetics (required aesthetics are in bold):
x: The x-coordinate of the seed point.y: The y-coordinate of the seed point.color: In geom_gradient_field, mapped tonorm(vectors) oravg_spd(streams) by default. In geom_gradient_field2, color is not mapped by default.length: In geom_gradient_field2 withtype = "vector", the computed vector norm.size,linetype,alpha: Additional aesthetics to control appearance.
Computed Variables
The following variables are computed internally by StatStreamField when generating the gradient field from a scalar function:
- norm
The Euclidean norm of the gradient at the evaluation point, \(\sqrt{f_x^2 + f_y^2}\). By default it is the color of vectors in geom_gradient_field and their length in geom_gradient_field2.
- avg_spd
For streams, the average speed along the stream, as in
geom_stream_field(). By default it is the color of streams in geom_gradient_field.
Examples
Si <- matrix(c(1, 0.75, 0.75, 1), nrow = 2)
f <- function(u) exp(-as.numeric(u %*% solve(Si) %*% u) / 2) / (2 * pi * det(Si))
ggplot() +
geom_gradient_field(fun = f, xlim = c(-3, 3), ylim = c(-3, 3))
# \donttest{
df <- expand.grid(x = seq(-3, 3, 0.1), y = seq(-3, 3, 0.1)) |>
transform(fxy = apply(cbind(x, y), 1, f))
ggplot() +
geom_raster(aes(x, y, fill = fxy), data = df) +
geom_gradient_field(fun = f, xlim = c(-3, 3), ylim = c(-3, 3)) +
coord_equal()
# over highest density regions, if ggdensity is installed
if (requireNamespace("ggdensity", quietly = TRUE)) {
fxy <- function(x, y) apply(cbind(x, y), 1, f)
ggplot() +
ggdensity::geom_hdr_fun(fun = fxy, xlim = c(-3, 3), ylim = c(-3, 3)) +
geom_gradient_field(fun = f, xlim = c(-3, 3), ylim = c(-3, 3)) +
coord_equal()
}
# }