【问题标题】:Strante interpretation of unit expression in grid网格中单位表达式的奇怪解释
【发布时间】:2019-11-08 10:59:53
【问题描述】:

我正在使用网格制作图形,并想绘制一些文本。我在指定文本坐标时遇到了问题。

具体来说,我发现我既可以使用直接单位,例如unit(1, "native"),也可以使用计算结果为单位的表达式,例如unit(1, "native") + unit(1, "mm")。但是一旦我在表达式中有两个本机单位,文本就不会绘制在我期望的位置,而是绘制在可能使用 npc 单位的位置。

在下面的 MWE 中,我希望将“3”打印在中间的右侧(以原生单位表示为 0),但它打印在最左侧。

 require(grid)

grid.newpage()
vp.data.region <- viewport(x = unit(0.5, "npc"), y = unit(0.5, "npc"), width = unit(0.8, "npc"), height = unit(0.8, "npc"), xscale=c(-1,1), yscale=c(-1,1), name = "data region")
pushViewport(vp.data.region)
grid.xaxis()
grid.yaxis()

grid.text("1", unit(0, "native"),unit(0, "native")) #places the text where it should be
grid.text("2", unit(0, "native") + unit(10, "mm"), unit(0, "native")) # it is possible to use an expression adding mixed units 
grid.text("3", unit(0.6, "native") - unit(0.5, "native") + unit(1, "mm") , unit(0, "native")) # suddenly, it looks like the unit expression is being interpreted as npc?

是什么导致了这个问题,我该如何避免它?请注意,使用单个表达式指定单位是非常困难的,因为我从一个已经指定为原生单位加上一些毫米的点开始,并且必须将文本放置在距它一定距离的位置,我必须再次使用本地单位和毫米。

【问题讨论】:

  • 也许这个问题可能会有所帮助? stackoverflow.com/questions/7045990/…。我不确定您到底要解决什么问题,所以我不确定该建议什么。
  • @MrFlick 当您查看我的 MWE 时,我正在尝试在 x=0.1native、y=0native 的坐标处打印文本“3”。相反,它会打印在屏幕上的其他位置。感谢您链接另一个问题,我还看不到如何使用它,因为我不想使用 npc 单位。
  • 哦,所以你真正的问题更像是为什么unit(.6, “native”) - unit(.5, “native”) 不等于unit(.1, “native”)
  • @MrFlick 是的,我期望它会与它相等。当我在脑海中进行天真的算术计算时,这就是我得到的结果,而且由于我是网格新手,我不知道为什么天真的计算不适用。而且,问题是,当我只有想要在 unit(0.6, "native") 左侧移动 0.5 个本机单位的信息时,我如何获得 unit(.1, "native") 的坐标。

标签: r graphics grid units-of-measurement


【解决方案1】:

基本上,计算的主要单位是npc 单位。当发生加法/减法时,每个值都转换为npc 单位。我们可以使用convertX 函数来查看这些值是如何产生的。当您使用本机单位时,这些值通过 xscale= 值映射到 npc 单位。请注意

convertX(unit(0.6, "native"), "npc")
# [1] 0.8npc
convertX(unit(0.5, "native"), "npc")
# [1] 0.75npc
convertX(unit(0.6, "native") - unit(0.5, "native"), "npc")
# [1] 0.0499999999999999npc

相比

convertX(unit(0.1, "native"), "npc")
# [1] 0.55npc

您不能在原生空间中使用npc 坐标进行消磁。如果你需要计算 0.6 左边的 0.5 个原生单位,那么你需要在原生空间中进行算术运算

convertX(unit(0.6 - 0.5, "native"), "npc")
# [1] 0.55npc

如果由于某种原因您不能这样做,那么您可以创建一个函数,该函数采用一个单位和一个移位并在该比例上进行算术运算。例如

nativeShift <- function(unit, shift) {
  stopifnot(class(unit)=="unit")
  stopifnot(attr(unit, "unit")=="native")
  stopifnot(is.numeric(shift))
  unit(unclass(unit) + shift, "native")
}

convertX(nativeShift(unit(.6, "native"), -.5), "npc")
# [1] 0.55npc

您的绘图示例看起来像

grid.text("3", nativeShift(unit(0.6, "native"), -0.5) + unit(1, "mm") , unit(0, "native"))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-08
    • 1970-01-01
    相关资源
    最近更新 更多