在 text
, 参数 adj
允许调整 labels
关于 x
和 y
.例如,adj
(0, 1) 的值表示左上对齐,即标签的左上角位于给定的 x
, y
协调。
这适用于默认字符扩展 cex = 1
.但是当我想要更大的标签时,通过增加 cex
创建,标签的位置从给定的坐标水平偏移,adj
使用。
这是一个小例子,演示了这一点:
# a basic plot
plot(1:10, asp = 1, cex = 1)
# a red reference mark at 5, 5
points(x = 5, y = 5, pch = 3, cex = 3, col = 'red')
# a label of default size (cex = 1), left top adjusted
text(x = 5, y = 5, labels = 'H', cex = 1, adj = c(0, 1))
# a large label (cex = 8) with same position and adjustment as above becomes offset horizontally
text(x = 5, y = 5, labels = 'H', cex = 8, adj = c(0, 1), col = rgb(0.1, 0.9, 0.1, 0.5))
水平偏移发生在左/右下/上对齐的所有组合中:
plot(1:10, cex = 1)
points(x = 5, y = 5, pch = 3, lwd = 4, cex = 4, col = 'red')
text(x = 5, y = 5, labels = "H", cex = 1, adj = c(0, 0))
text(x = 5, y = 5, labels = "H", cex = 1, adj = c(0, 1))
text(x = 5, y = 5, labels = "H", cex = 1, adj = c(1, 0))
text(x = 5, y = 5, labels = "H", cex = 1, adj = c(1, 1))
text(x = 5, y = 5, labels = "H", cex = 8, adj = c(0, 0), col = "green")
text(x = 5, y = 5, labels = "H", cex = 8, adj = c(0, 1), col = "green")
text(x = 5, y = 5, labels = "H", cex = 8, adj = c(1, 0), col = "green")
text(x = 5, y = 5, labels = "H", cex = 8, adj = c(1, 1), col = "green")
cex
时如何避免标签水平偏移> 1?
最佳答案
这个问题可能有点难以解决。首先尝试解释原因,然后是潜在的解决方案。
正如 R 董事会成员 Brian Ripley 在 R 帮助邮件列表中所写here :
“R 图形中的文本字符串直接以指定的字体绘制,而不是作为单个字母绘制”。
任何字体中的字母(或数字、标点和形状)都由字形表示。每个字形在两侧都有水平空间,即所谓的左右侧轴承。见例如here , here ('glyph metrics') , 和 here .
尽管在使用 cex = 1
时非常小,但侧轴承会导致您的绘图中出现偏移。 .当您增加绘图中“字形”的大小时(使用 cex
),不仅字符本身的大小会增加,而且大小轴承的绝对宽度也会增加。
里普利因此得出结论:
“所以你对 R 中的字母间距无能为力。”
This Q&A显示了减少字母之间空格的技巧。不过,拆除前导左侧轴承可能会更棘手。
一个潜在的解决方案可能是使用 systemfonts::shape_string
捕获左轴承,然后相应地调整 x 位置。
这是一些带有坐标的字符串的示例。使用原始 x 值(浅灰色)和 x 值减去轴承(深灰色)绘制字符串(带有“大” cex
)。
d <- data.frame(x = 1:3, y = 1:3, labs = c("Where", "is", "Here"))
# set pointsize, cex and resolution
ps <- 12
cex <- 8
res <- 72
# calculate left bearing in pixels
left_bear_px <- shape_string(d$labs, size = ps * cex)$metrics$left_bearing
# open device
png("pp.png", width = 10, height = 5, units = "in", res = res)
# plot with "cross hair"
plot(x = d$x, y = d$y, pch = 3, cex = 3, col = "red", xlim = c(0, 5), ylim = c(0, 3))
# convert unit of bearing from pixel to xy: multiply by xy / pixel ratio
left_bear_xy <- left_bear_px * ((par("cxy") / par("cra"))[1])
# add text at original positions (light grey)
text(x = d$x, y = d$y, labels = d$labs,
cex = cex, adj = c(0, 1), col = grey(0.6, alpha = 0.5))
# x values with left bearing removed (dark grey)
text(x = d$x - left_bear_xy, y = d$y, labels = d$labs,
cex = cex, adj = c(0, 1), col = grey(0.1, alpha = 0.5))
dev.off()
关于r - 在文本中使用 adj 参数时, "large"标签的水平对齐会发生偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30152201/