如何在ggplot的X轴下方及X、Y轴标题旁添加箭头?
问题
需要在ggplot绘制的图表中实现以下效果:
- 在X轴下方添加箭头
- 在X轴标题和Y轴标题旁添加箭头
当前使用的ggplot代码如下:
quadrant <- ggplot(quadrants, aes(x=Ampolla, y=Energia, label=Branca_percIPI))+ coord_fixed() + coord_cartesian(clip = 'off') + scale_x_continuous(expand = c(0, 0), limits = c(-5, 50)) + scale_y_continuous(expand = c(0, 0), limits = c(0,50))+ geom_vline(xintercept = 11.3, color = "grey50", size=1.2) + geom_hline(yintercept = 17.7, color = "grey50", size=1.2) + geom_text_repel(size = 7, colour = "#2896BA", min.segment.length = Inf, hjust="right", nudge_x=0.9, nudge_y=1.5, force=1, arrow = arrow(length=unit(0.5,"cm"), ends="first"), lineheight = 1)+ geom_point(colour="#2896BA", size=3.5)+ labs(title = "Incidència dels colls d'ampolla i dependència energètica total", subtitle="(% de variació interanual de l'IPI*, % d'empreses afectades pels colls d'ampolla i % de dependència energètica)", x = "Colls d'ampolla (% d'empreses afectades)**", y = "Dependència energètica total (%)")+ annotation_custom(segmentsGrob(c(0.3, -0.1), c(-0.085, 0.28), c(1, -0.1), c(-0.085, 0.28), gp = gpar(lwd = 2), arrow = arrow(length = unit(2.5, 'mm'))))
解决方案
通过annotation_custom结合grid包的segmentsGrob可精准控制箭头位置,配合已开启的coord_cartesian(clip = 'off'),就能让图表外的箭头正常显示。以下是调整后的完整代码:
library(ggplot2) library(grid) quadrant <- ggplot(quadrants, aes(x=Ampolla, y=Energia, label=Branca_percIPI))+ coord_fixed() + coord_cartesian(clip = 'off') + scale_x_continuous(expand = c(0, 0), limits = c(-5, 50)) + scale_y_continuous(expand = c(0, 0), limits = c(0,50))+ geom_vline(xintercept = 11.3, color = "grey50", size=1.2) + geom_hline(yintercept = 17.7, color = "grey50", size=1.2) + geom_text_repel(size = 7, colour = "#2896BA", min.segment.length = Inf, hjust="right", nudge_x=0.9, nudge_y=1.5, force=1, arrow = arrow(length=unit(0.5,"cm"), ends="first"), lineheight = 1)+ geom_point(colour="#2896BA", size=3.5)+ labs(title = "Incidència dels colls d'ampolla i dependència energètica total", subtitle="(% de variació interanual de l'IPI*, % d'empreses afectades pels colls d'ampolla i % de dependència energètica)", x = "Colls d'ampolla (% d'empreses afectades)**", y = "Dependència energètica total (%)")+ # X轴下方的双向箭头 annotation_custom(segmentsGrob(x0 = 0.05, y0 = -0.08, x1 = 0.95, y1 = -0.08, gp = gpar(lwd = 2), arrow = arrow(length = unit(2.5, 'mm'), ends = "both")))+ # X轴标题上方的箭头(指向标题) annotation_custom(segmentsGrob(x0 = 0.5, y0 = -0.12, x1 = 0.5, y1 = -0.09, gp = gpar(lwd = 2), arrow = arrow(length = unit(2, 'mm'), ends = "last")))+ # Y轴标题右侧的箭头(指向标题) annotation_custom(segmentsGrob(x0 = -0.08, y0 = 0.5, x1 = -0.05, y1 = 0.5, gp = gpar(lwd = 2), arrow = arrow(length = unit(2, 'mm'), ends = "last")))+ # 调整边距避免箭头被截断 theme(plot.margin = margin(10, 10, 40, 40))
核心调整说明:
segmentsGrob采用归一化坐标(0-1范围,(0,0)对应绘图区左下角,(1,1)对应右上角),修改x0,y0,x1,y1可灵活调整箭头位置ends参数控制箭头方向:"both"为双向箭头,"last"为单向箭头指向终点- 新增
theme(plot.margin)增大底部和左侧边距,确保箭头不被画布截断
内容的提问来源于stack exchange,提问作者Maria
相关产品推荐
相关产品推荐

