我了解您打算创建一个图例,显示代表主图中向量的长度/速度/速度的箭头。有一个非常相似的问题,但给定的答案(免责声明:我的答案)尚未被投票或接受,因此我对于是否将这个问题作为重复项关闭感到犹豫。
建议的解决方案是通过注释创建假图例。
注意:你对向量长度的计算在我看来是错误的。 (这也是为什么我的情节中图例中的箭头长度如此长的原因)。从您提供的数据中很难猜测您想要的向量长度,但是计算线段长度的公式是
xend = x + 速度 * cos(方向[角度] * pi / 180)
yend = y + 速度 * sin(方向[角度] * pi / 180)
其中 0 度指向右侧,这是更常见的约定,但可能并不总是如此。
library(tidyverse)
data <- data.frame(
long = 1:4,
lat = 2,
wd_x = cos(1:4),
wd_y = sin(1:4),
ws = 1:4
)
## I prefer to prepare data outside of ggplot calls
df <- data %>%
mutate(xend = long + wd_x * ws / 5,
yend = lat + wd_y * ws / 5)
## defining x or y coordinates for your annotation can be daunting.
## First get x and y range
ylims <- range(c(df$lat, df$yend))
xlims <- range(c(df$long, df$xend))
df_leg <-
data.frame(
ws = c(1, 5),
y = ylims[1] - c(ylims[1]/1.6, ylims[1]/1.3),
x = xlims[1]
) %>%
## for the label x coord
mutate(xend = x + ws)
## your plot, just slightly modified
ggplot(df) +
geom_segment(aes(x = long, y = lat,
xend = xend, yend = yend),
arrow = arrow(length = unit(0.15, "cm"))) +
geom_segment(
data = df_leg,
aes(
x = x, y = y, xend = xend,
yend = y
),
## you need to experiment with the arrow head length, I'd pass a vector
arrow = arrow(length = unit(3:4, "pt")), show.legend = FALSE
) +
geom_text(
data = df_leg, aes(x = xend, y = y, label = paste(ws, "m/s")),
hjust = -.1
) +
coord_fixed(ratio = 1, xlim = xlims, ylim = ylims, clip = "off") +
theme(legend.position = "none",
plot.margin = margin(r = 2.6, unit = "in"))
![](https://i.stack.imgur.com/Fbj4a.png)
Created on 2023-03-23 with reprex v2.0.2