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

如何使用R的grid::pattern函数旋转图案的重复方向?

grid包pattern功能的图案重复方向旋转问题

我正在研究grid包的新pattern功能,目前已实现矩形的交叉填充:

library(grid)

# 注意:x和y使用"cm"这类绝对坐标无效
cross <- grobTree(
  linesGrob(x = unit(c(0,1), "npc"), y = unit(c(0,1), "npc")),
  linesGrob(x = unit(c(0,1), "npc"), y = unit(c(1,0), "npc"))
)

cpat <- pattern(
  cross,
  width = unit(1, "cm"),
  height = unit(1, "cm"),
  extend = "repeat"
)

rect <- rectGrob(
  width = unit(5, "cm"),
  height = unit(5, "cm"),
  gp = gpar(fill = cpat)
)

grid.newpage()
grid.draw(rect)

但旋转对象时会出现显示异常:

grid.newpage()
grid.draw(grobTree(rect, vp = viewport(angle = 20)))

而旋转图案本身时,图案的重复方向并未随之旋转:

vp <- viewport(angle = 30)
cross <- grobTree(
  linesGrob(x = unit(c(0,1), "npc"), y = unit(c(0,1), "npc")),
  linesGrob(x = unit(c(0,1), "npc"), y = unit(c(1,0), "npc")),
  vp = vp
)

cpat <- pattern(
  cross,
  width = unit(1, "cm"),
  height = unit(1, "cm"),
  extend = "repeat"
)

rect <- rectGrob(
  width = unit(5, "cm"),
  height = unit(5, "cm"),
  gp = gpar(fill = cpat)
)

grid.newpage()
grid.draw(rect)

解决方法

要让图案的重复方向跟着旋转,需要将旋转视口应用到pattern对象本身,而非组成图案的grob上。这样整个图案的重复网格系统会同步旋转,而不仅仅是单个图案单元:

library(grid)

# 创建用于图案旋转的视口
pattern_vp <- viewport(angle = 30)

# 定义交叉线图案(保持相对坐标)
cross <- grobTree(
  linesGrob(x = unit(c(0,1), "npc"), y = unit(c(0,1), "npc")),
  linesGrob(x = unit(c(0,1), "npc"), y = unit(c(1,0), "npc"))
)

# 将旋转视口传入pattern的vp参数
cpat <- pattern(
  cross,
  width = unit(1, "cm"),
  height = unit(1, "cm"),
  extend = "repeat",
  vp = pattern_vp
)

rect <- rectGrob(
  width = unit(5, "cm"),
  height = unit(5, "cm"),
  gp = gpar(fill = cpat)
)

grid.newpage()
grid.draw(rect)

另外,若要避免旋转整个grob时的显示异常,优先选择旋转pattern而非外层grob,这样图案的填充会匹配旋转后的坐标系统,不会出现错位或拉伸。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 09:05:24