2013-08-04 21 views
2

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

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

您可以使用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) 
+0

很酷,谢谢你的回答。 'mai'的默认值是多少? 'par'的帮助页面提供了'mar'的默认值,但是我找不到'mai'。 –

+0

'mai'和'mar'包含相同的信息,但以不同的单位。 'mar'的默认值总是相同的,但'mai'的相应值可能取决于设备,字体等。 –