You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在R的色条图例中添加箭头与标签?解决分图显示问题

问题解决:为R绘图色条图例添加箭头与标签并合并图层

问题说明

需要为极地绘图的色条图例添加方向箭头(对应数值增减)和标签,同时解决现有代码无法将色条与箭头绘制在同一张图的问题。

解决步骤

  1. 合并图层核心操作:原代码将主绘图和箭头文字分开绘制,需把主图作为底层嵌入ggdraw画布,再叠加箭头与文字元素。
  2. 定位调整:ggdraw使用0-1的相对坐标,需根据主图图例的实际位置微调箭头、文字的坐标,确保对齐色条。
  3. 图例位置适配:可微调主图的图例位置,给箭头和标签预留空间。

修改后的完整代码

# 先将主图保存为变量p
p <- ggpolar(pole = "N", max.lat = 90, min.lat = 30, 
    land.fill.colour = "transparent", land.outline.colour = "#343434", 
    plt.lat.labels = FALSE,size = 0.8) +
ggtitle("C") +
theme(plot.title = element_text(hjust = 0, family = "Arial", size = 18,face = "bold")) +
geom_tile(data = ae_raster_S3_df, aes(x = lon, y = lat, fill = change_ratio),alpha = 0.8) + 
geom_point(data = result_df_s3, aes(x = lon, y = lat), color = "#343434", size = 0.5) +
scale_fill_stepsn(colors = custom_colors,
                breaks = break_points, 
                labels = c("-5", "-4", "-3", "-2", "-1", "0", "1", "2", "3", "4", "5"),
                limits = c(-6, 6),
                name = expression(AE~('%'~ decade^{-1})),
                na.value = "transparent",
                guide = guide_colorbar(barwidth = 1, barheight = 25, direction = "vertical",
                                       title.position = "right", title.hjust=0.5, label.position = "right", title.theme = element_text(family = "Arial", size = 16, angle = 90),label.theme = element_text(family = "Arial", size = 12))) +
theme(
plot.background = element_rect(fill = NA, color = NA),
panel.background = element_rect(fill = NA, color = NA),
# 微调图例位置,给箭头预留左侧空间
legend.position = c(0.82, 0.5),
legend.key.width = unit(2, "line"),
legend.key.height = unit(0.5, "line"),
legend.title = element_text(family = "Arial", size = 12),
legend.text = element_text(size = 12),
axis.title = element_blank(),
axis.text = element_text(family = "Arial", size = 12),
axis.ticks = element_blank()
)

# 使用ggdraw合并主图与箭头、文字元素
ggdraw(p) +
draw_text("Decreasing", x = 0.75, y = 0.75, hjust = 0, family = "Arial",color = "#D15547", size = 16, angle=90) +
draw_text("Increasing", x = 0.75, y = 0.25, hjust = 0, family = "Arial",color = "#3C87BD", size = 16, angle=90) +
draw_text("Seasonality", x = 0.88, y = 0.5, hjust = 0, family = "Arial",color = "black", size = 16, angle=90) +
# 调整箭头坐标,对齐色条上下端
draw_line(x = c(0.72, 0.72), y = c(0.52, 0.22), 
        arrow = arrow(length = unit(0.1, "inches")), color = "#3C87BD", size = 1) +
draw_line(x = c(0.72, 0.72), y = c(0.48, 0.78), 
        arrow = arrow(length = unit(0.1, "inches")), color = "#D15547", size = 1)

关键修改说明

  • 将主图赋值给p,通过ggdraw(p)把主图作为底层画布,确保所有元素在同一绘图区域。
  • 微调legend.position和箭头、文字的坐标值,可根据实际绘图尺寸进一步调整至最佳对齐效果。
  • 箭头的起点/终点坐标对应色条的中间(0值位置)向上下延伸,匹配数值增减的方向。

内容的提问来源于stack exchange,提问作者Ruijie Wang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 21:07:33