ggplot2绘制风向箭头叠加图:调范围与去背景轴网
解决ggplot2风向箭头图的范围控制与元素隐藏问题
问题分析
原代码存在几个关键问题导致需求未实现:
- 包名错误:
library(ggplot)应为library(ggplot2),可能引发功能异常 - 箭头方向未结合风向数据:固定的
xend = lon + 0.08无法体现真实风向 - 绘图范围设置未正确整合到绘图流程中
- 主题清理不彻底:未完全移除坐标轴、背景等元素
修正后的完整代码
library(ggplot2) library(dplyr) wind_data <- structure(list(lon = c(8.87312091729266, 8.71871388830953, 10.5679127453358, 10.7216122406487, 10.4141464047873, 10.5679127453358, 10.1064188710028, 11.3357135330171, 11.4890576651767, 11.1822955254471), lat = c(54.6482360923283, 54.5584019137964, 54.2888913181823, 54.2888913181823, 54.1990517614177, 54.1990517614177, 54.0193686018903, 53.6599860593553, 53.6599860593553, 53.5701370357575), dd = c(238, 235, 238, 232, 232, 236, 239, 240, 240, 240)), class = "data.frame", row.names = c(NA, -10L)) # 转换风向为箭头终点坐标(风向是风的来向,箭头指向风的去向) wind_data <- wind_data %>% mutate( # 将方位角转换为弧度,适配ggplot笛卡尔坐标系的角度方向 rad = (90 - dd) * pi / 180, # 自定义箭头长度,可按需调整 arrow_len = 0.1, xend = lon + arrow_len * cos(rad), yend = lat + arrow_len * sin(rad) ) p <- ggplot(wind_data, aes(x = lon, y = lat)) + # 绘制风向箭头 geom_segment(aes(xend = xend, yend = yend), arrow = arrow(length = unit(0.1, "cm")), size = 0.25) + # 强制设置绘图显示范围,不过滤数据 coord_cartesian(xlim = c(3.604383, 14.60482), ylim = c(47.07157, 54.73807)) + # 一键清除所有坐标轴、网格、背景 theme_void() + # 兜底设置确保无额外元素 theme( plot.background = element_blank(), panel.background = element_blank(), legend.position = "none" ) # 导出透明背景PNG,适合后续叠加 ggsave("wind_arrows.png", p, width = 8, height = 10, dpi = 300, bg = "transparent") # 导出透明背景TIFF,满足高质量叠加需求 ggsave("wind_arrows.tiff", p, width = 8, height = 10, dpi = 300, bg = "transparent")
关键修正说明
- 风向坐标转换:通过三角函数将气象方位角转换为笛卡尔坐标系下的箭头终点,确保箭头方向符合风向定义(风从
dd方向吹来,箭头指向去向) - 范围控制:
coord_cartesian()直接限定绘图显示范围,不会过滤原始数据,完全匹配叠加层需求 - 主题清理:
theme_void()一键移除所有冗余元素,补充透明背景设置,确保输出仅保留箭头 - 导出配置:设置
bg = "transparent"生成透明底图,方便后续叠加到其他图层
内容的提问来源于stack exchange,提问作者Andreas
相关产品推荐
相关产品推荐

