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

R语言中如何旋转NeighborNet绘图标签以避免重叠?

NeighborNet 绘图标签旋转解决方案

默认情况下,phangorn包中绘制NeighborNet的函数不支持自动沿边旋转标签,但可以通过手动计算角度实现需求。以下是修改后的完整代码:

library(stylo)
library(phangorn)
data("galbraith")
dist.mx <- as.matrix(dist.wurzburg(galbraith))
nnet <- phangorn::neighborNet(dist.mx)                     
par(mar = c(0,0,0,0))

# 绘制不带标签的网络图
plot(nnet,
     type = "equal angle", 
     tip.offset = 0.9,
     edge.color = "grey20",
     edge.width = 1,
     font = 1,
     cex = 0.7,
     use.edge.length = F,
     show.tip.label = FALSE # 关闭默认标签显示
)

# 提取末端节点与对应边的坐标信息
tip_labels <- nnet$tip.label
tip_count <- length(tip_labels)
# 末端节点的坐标
tip_coords <- nnet$plot$xy[1:tip_count, ]
# 连接末端节点的内部边节点坐标
edge_node_coords <- nnet$plot$xy[nnet$edge[nnet$edge[,2] <= tip_count, 1], ]

# 计算每个标签的旋转角度(弧度转角度)
rotation_angles <- atan2(tip_coords[,2] - edge_node_coords[,2], 
                         tip_coords[,1] - edge_node_coords[,1]) * (180/pi)
# 调整角度,避免文字倒置,保证可读性
rotation_angles <- ifelse(rotation_angles > 90 & rotation_angles < 270, 
                          rotation_angles + 180, rotation_angles)

# 添加旋转后的标签
text(tip_coords[,1], tip_coords[,2], labels = tip_labels, 
     cex = 0.7, font = 1, srt = rotation_angles, adj = c(0.5, 0.5))

关键步骤说明:

  • 先绘制无标签的网络图,规避默认水平标签的重叠问题
  • 通过末端节点和对应内部边节点的坐标差,计算出标签应旋转的角度
  • 对角度进行修正,防止文字倒置,确保阅读顺畅

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 10:04:51