2

我想为我的特定目的编写一个绘图函数,并将 y 标签放在左边距。然而,这些标签的长度可能会有很大差异,并且取决于用户提出的模型术语。出于这个原因,我想测量最长标签的宽度并相应地设置左边距宽度。我找到了该strwidth函数,但我不明白如何将其输出单位转换为mar参数单位。一个例子:

label <- paste(letters, collapse = " ")  # create a long label
par(mar = c(5, 17, 4, 2) + 0.1)  # 17 is the left margin width
plot(1:2, axes = FALSE, type = "n")  # stupid plot example

# if we now draw the axis label, 17 seems to be a good value:
axis(side = 2, at = 1, labels = label, las = 2, tck = 0, lty = 0)

# however, strwidth returns 0.59, which is much less...
lab.width <- strwidth(label)  # so how can I convert the units?
4

1 回答 1

4

您可以使用mai而不是mar指定以英寸为单位的距离(而不是“线”)。

par(mai = c(1, strwidth(label, units="inches")+.25, .8, .2))
plot(1:2, axes=FALSE)
axis(side = 2, at = 1, labels = label, las = 2, tck = 0, lty = 0)

您可以通过除以 来计算线和英寸之间的转换mar因子mai

inches_to_lines <- ( par("mar") / par("mai") )[1]  # 5
lab.width <- strwidth(label, units="inches") * inches_to_lines
par(mar = c(5, 1 + lab.width, 4, 2) + 0.1) 
plot(1:2, axes=FALSE)
axis(side = 2, at = 1, labels = label, las = 2, tck = 0, lty = 0)
于 2013-08-04T09:07:05.707 回答