自动找出&pos; pos' pos的正确值。用于绘制轴标签

时间:2017-01-15 01:45:33

标签: r plot

在下面示例的最后一行中,我必须手动为pos尝试几个不同的值,然后才能找到正确的'在上一行中已经绘制的labels之外的值。有没有办法自动找出pos的正确值?

dev.off()
windows(width = 8, height = 6)
par(mai = c(0.3, 2.5, 0.3, 0.3)) #bottom, left, top and right
set.seed(42)
plot(rnorm(15,10,1),rnorm(15,10,1), type = "p",
     ylim = c(5,15), xlim = c(5,15), xlab = "", ylab = "",
     xaxt = "n", yaxt = "n", yaxs="i", xaxs="i")
axis(2, at = c(5,10,15), labels = c("This one", "Particularly long one", "two"), las = 2)
axis(2, at = 10, pos = 2, labels = "Y Axis Label", font = 2, tick = FALSE, cex.axis = 1.5)

1 个答案:

答案 0 :(得分:1)

您可以抓取par(usr)[1]并减去长标签的strwidth以获得排名:

dev.off()
windows(width = 8, height = 6)
par(mai = c(0.3, 2.5, 0.3, 0.3)) #bottom, left, top and right
set.seed(42)
plot(rnorm(15, 10, 1),rnorm(15, 10, 1), type = "p",
     ylim = c(5, 15), xlim = c(5, 15), xlab = "", ylab = "",
     xaxt = "n", yaxt = "n", yaxs= "i", xaxs= "i")
axis(2, at = c(5, 10, 15),
     labels = c("This one", "Particularly long one", "two"), las = 2)

# get the position based on the long string width and par('usr')[1]
pos <- par('usr')[1] - strwidth("Particularly long one")

axis(2, at = 10, pos = pos,
     labels = "Y Axis Label", font = 2, tick = FALSE, cex.axis = 1.5)

enter image description here

当然,如果您在此之后以交互方式调整图像大小,则所有投注均已关闭。