gpt4 book ai didi

r - 什么控制 strwidth 中的表观缓冲区?

转载 作者:行者123 更新时间:2023-12-04 04:11:28 24 4
gpt4 key购买 nike

我正在尝试将文本标签包裹在一个矩形中。

这是一个带有标签的简单图:

x = mtcars$wt
y = mtcars$mpg
l = rownames(mtcars)

plot(x, y)
text(x, y, l, adj = .5) # i.e., the default

enter image description here

我可以像这样成功地使用 strwidthstrheight 来完成包装:

delx = strwidth(l, cex = par('cex'))
dely = strheight(l, cex = par('cex'))

rect(x - .5*delx, y - .5*dely, x + .5*delx, y + .5*dely)

enter image description here

注意每个标签左右两侧的空白“间隙”。现在,这很好,但在尝试考虑情节中的 adj 时会导致问题:

adj = c(0, .5)
plot(x, y)
text(x, y, l, adj = adj)
rect(
x - adj[1L]*delx, y - adj[2L]*dely,
x + (1-adj[1L])*delx, y + (1-adj[2L])*dely
)

enter image description here

盒子的方向调整得很好,但它看起来是一个准确的转换,我需要进一步考虑创建“缓冲区”宽度的因素。

那是什么?我还没有在 ?par 或 ?strwidth 中看到任何内容。

最佳答案

没有内部宽度缓冲区。只是你需要在当前设备的上下文中计算strwidth。当您在绘制绘图后调整图形设备大小时,矩形将调整大小但文本不会。这将导致文本周围的明显空间随窗口大小而变化。

只要您在绘制绘图之前仔细指定设备尺寸,并重新计算该设备上文本的 strwidth,您的代码就应该在文本周围生成舒适的框。您也可以在不影响居中的情况下添加固定边距,并且这些都不需要尚不可用的信息。

这是一个用于说明目的的函数,它允许完全控制文本周围的框:

michael_plot <- function(width = 9, height = 6, adj = c(0.5, 0.5), margin = 0)
{
dev.new(width = width, height = height, unit = "in", noRStudioGD = TRUE)
plot(x, y)
delx <- strwidth(l, cex = par('cex'))
xmarg <- strwidth("M", cex = par('cex')) * margin
dely <- strheight(l, cex = par('cex'))
ymarg <- strheight("M", cex = par('cex')) * margin / 2
text(x, y, l, adj = adj)
rect(x - adj[1] * delx - xmarg,
y - adj[2] * dely - ymarg,
x + (1 - adj[1]) * delx + xmarg,
y + (1 - adj[2]) * dely + ymarg)
}

从默认开始:

michael_plot()

enter image description here

盒子非常合适;事实上,它们离文本太近了,因此我们应该添加边距以使其更易读:

michael_plot(margin = 1)

enter image description here

但重要的是,我们可以使用 adj 安全地移动它们,同时保持它们居中:

michael_plot(margin = 1, adj = c(0, 0.5))

enter image description here

关于r - 什么控制 strwidth 中的表观缓冲区?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61651361/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com