set.seed(1234)
n <- 10
# Generate wind data in polar coordinates
data <- data.frame(
x = rnorm(n),
y = rnorm(n),
dir = runif(n, -pi, pi), # angle in radians
spd = rchisq(n, df = 2) # speed
) |>
transform(fx = spd * cos(dir), fy = spd * sin(dir))
# Using fx/fy to compute endpoints
ggplot(data, aes(x, y)) +
geom_vector(aes(fx = fx, fy = fy))
# Using angle (in radians) and distance to compute endpoints
ggplot(data, aes(x, y)) +
geom_vector(aes(angle = dir, distance = spd))
# Using angle_deg (in degrees) and distance to compute endpoints
vectors3 <- data.frame(
x = c(0, 1, 2),
y = c(0, 1, 2),
angle_deg = c(0, 90, 45),
angle = c(0, pi/2, pi/4),
distance = c(3, 4, 5)
)
ggplot(vectors3, aes(x, y)) +
geom_vector(aes(angle_deg = angle_deg, distance = distance))
# Basic usage with explicit start and end points:
vectors1 <- data.frame(
x = c(0, 1, 2),
y = c(0, 1, 2),
xend = c(3, 1, 5),
yend = c(0, 5, 6)
)
ggplot(vectors1, aes(x = x, y = y, xend = xend, yend = yend)) +
geom_vector()
# Using center = TRUE to recenter vectors:
ggplot(vectors1, aes(x = x, y = y, xend = xend, yend = yend)) +
geom_vector(center = TRUE)
# Using normalize = TRUE to adjust vectors to unit length:
ggplot(vectors3, aes(x = x, y = y, angle = angle, distance = distance)) +
geom_vector(normalize = TRUE)
# Using geom_vector2, which adds a default mapping for `length`
ggplot(vectors1, aes(x = x, y = y, xend = xend, yend = yend)) +
geom_vector2()
Run the code above in your browser using DataLab