# \donttest{
# Define a true vector field function
f <- function(u) {
x <- u[1]; y <- u[2]
c(x^2 - y^2, x^2 + y^2 - 2)
}
# Alternative example function
f <- function(u) c(-u[2], u[1])
# Visualize the vector field
ggplot() + geom_stream_field(fun = f, xlim = c(-2, 2), ylim = c(-2, 2))
# Generate design points
n <- 20
df <- data.frame(x = runif(n, -2, 2), y = runif(n, -2, 2))
# Sample function values at design points
fdf <- as.data.frame(t(apply(df, 1, f)))
colnames(fdf) <- c("fx", "fy")
df <- cbind(df, fdf)
# Visualize raw vector field data
ggplot(df) + geom_vector(aes(x, y, fx = fx, fy = fy))
# Add smoothed layer using default model
ggplot(df) +
geom_vector(aes(x, y, fx = fx, fy = fy)) +
geom_stream_smooth(formula = cbind(fx, fy) ~ x * y)
# Use a more complex polynomial model
ggplot(df) +
geom_vector(aes(x, y, fx = fx, fy = fy)) +
geom_stream_smooth(formula = cbind(fx, fy) ~ poly(x, 2) * poly(y, 2), data = df)
# Fit a linear model and use it for prediction
fhat <- function(u) {
model <- lm(cbind(fx, fy) ~ x * y, data = df)
predict(model, newdata = data.frame(x = u[1], y = u[2])) |> as.numeric()
}
# Visualize estimated field with the raw vector field
ggplot(df) +
geom_stream_field(fun = fhat, normalize = FALSE, color = "#3366FF") +
geom_vector(aes(x, y, fx = fx, fy = fy))
# Generate a hexagonal grid
hex_lattice <- grid_hex(xlim = c(-5, 5), ylim = c(-5, 5), d = 1)
# Use the hexagonal grid in geom_stream_field
ggplot(data = df) +
geom_vector(aes(x, y, fx = fx, fy = fy), color = "black", normalize = FALSE) +
geom_stream_smooth(eval_points = hex_lattice)
# user specified point
eval_pts <- data.frame(x = c(0, 1), y = c(2, -1))
ggplot(data = df) +
geom_vector(aes(x, y, fx = fx, fy = fy), color = "black", normalize = FALSE) +
geom_stream_smooth(eval_points = eval_pts)
# }
Run the code above in your browser using DataLab