问题
In text
, the argument adj
allows adjustment of the labels
with respect to x
and y
. For example, adj
values of (0, 1) means left-top alignment, i.e. the left, top corner of the label is placed at the given x
, y
coordinate.
This works fine with the default character expansion cex = 1
. But when I want a larger label, created by increasing cex
, the position of label is offset horizontally from the given coordinate and adj
ustment.
Here is a small example which demonstrates this:
# 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))
The horizontal offset occurs for all combinations of left/right bottom/top alignments:
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")
How to avoid the horizontal offset of labels when cex
> 1?
回答1:
The problem may be a bit tricky to solve. Here's an attempt to explain why. As written by R board member Brian Ripley on the R help mailing list here:
"Text strings in R graphics are plotted directly in the font specified and not as individual letters".
Letters (or numbers, punctuations and shapes) in any font are represented by glyphs. Each glyph has horizontal spaces on either side, the so-called left and right side bearings. See e.g. here, here ('glyph metrics'), and here.
It is the side bearings which causes the offset in your plot, albeit very small when using cex = 1
. When you increase the size of the 'glyph' in your plot (using cex
), not only the character itself is increasing in size, but also the absolute width of the size bearings.
And Ripley thus concludes:
"so there is nothing you can do about letter spacing in R."
This Q&A shows a hack to reduce space between letters. To remove the leading left side bearing might be more tricky though.
来源:https://stackoverflow.com/questions/30152201/horizontal-alignment-of-large-labels-is-offset-when-using-adj-argument-in-text