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

如何调整R语言diagram包plotmat中介图中c框的位置?

调整diagram包plotmat函数中单个框的位置方法

你目前用plotmat函数生成的是2x2网格布局,没法直接通过参数调整单个框的位置。要实现你草图里的布局(a、b在上排左右分布,d在下排居中,c在b的右下方、d的右上方),得用diagram包的底层绘图函数手动绘制每个元素,具体步骤如下:

原代码问题说明

你的原代码基于2x2矩阵生成固定网格布局,所有框被绑定在网格节点上:

library(diagram)
data <- c(0, 0, "'4'",0,
          "'1'",0,  0, 0, 
          0,0,0,0,
          "'2'","'3'", "'5'" ,0)
M<- matrix (nrow=4, ncol=4, byrow = TRUE, data=data)
plot<- plotmat (M, pos=c(2,2), 
                name= c("a", "b", "c", "d"), 
                box.type = "rect", box.size = 0.15, box.prop=0.5,  curve=0, shadow.size = 0)

手动自定义布局的解决方案

放弃plotmat的自动布局,用textbox()绘制每个框,arrow()绘制连接线,精准控制每个元素的坐标:

library(diagram)

# 初始化绘图区域,设置坐标范围
plot.new()
plot.window(xlim = c(0, 1), ylim = c(0, 1))

# 定义每个框的坐标与名称
boxes <- list(
  a = list(x = 0.2, y = 0.8, name = "a"),
  b = list(x = 0.4, y = 0.8, name = "b"),
  c = list(x = 0.6, y = 0.4, name = "c"),
  d = list(x = 0.4, y = 0.2, name = "d")
)

# 批量绘制文本框,保持和原代码一致的样式
for (box in boxes) {
  textbox(box$name, x = box$x, y = box$y, 
          box.type = "rect", box.size = 0.15, box.prop = 0.5, shadow.size = 0)
}

# 绘制连接线及标注
# a -> d(标注'2')
arrow(from = c(boxes$a$x, boxes$a$y - 0.1), to = c(boxes$d$x, boxes$d$y + 0.1), 
      curve = 0, arr.pos = 0.5, arr.type = "triangle")
text(x = 0.3, y = 0.5, labels = "'2'")

# b -> d(标注'3')
arrow(from = c(boxes$b$x, boxes$b$y - 0.1), to = c(boxes$d$x, boxes$d$y + 0.1), 
      curve = 0, arr.pos = 0.5, arr.type = "triangle")
text(x = 0.4, y = 0.5, labels = "'3'")

# a -> b(标注'1')
arrow(from = c(boxes$a$x + 0.075, boxes$a$y), to = c(boxes$b$x - 0.075, boxes$b$y), 
      curve = 0, arr.pos = 0.5, arr.type = "triangle")
text(x = 0.3, y = 0.8, labels = "'1'")

# b -> c(标注'4')
arrow(from = c(boxes$b$x + 0.075, boxes$b$y - 0.05), to = c(boxes$c$x - 0.075, boxes$c$y + 0.05), 
      curve = 0, arr.pos = 0.5, arr.type = "triangle")
text(x = 0.5, y = 0.6, labels = "'4'")

# c -> d(标注'5')
arrow(from = c(boxes$c$x, boxes$c$y - 0.1), to = c(boxes$d$x + 0.075, boxes$d$y + 0.1), 
      curve = 0, arr.pos = 0.5, arr.type = "triangle")
text(x = 0.5, y = 0.3, labels = "'5'")

调整说明

  • 你可以修改boxes列表里的x、y值,精细调整每个框的位置,直到匹配你的草图样式
  • text()函数的坐标参数可以微调标注文本的位置,保证和箭头对齐
  • 所有样式参数(box.type、box.size等)和原代码一致,保持视觉统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 18:03:21