问题描述
我想知道如何在R中添加一个字母来引用图形,但又不总是更改y和x值.我希望文本始终位于相同的位置(在相同的基线上,并且在x轴上的相对距离相同.
I want to know how it's possible to add a letter to reference a graph in R, but without always changing the y and x value. I want the text to be always at the same place (on the same baseline, and at the same relative distance on the x axis.
set.seed(1234)
plot(2,3)
text(x = 1.5,y = 4, "A", font = 2 )
plot(rnorm(100))
text(x = 1.5,y = 2, "B", font = 2)
如您所见,字母B在x轴上的距离不同,并且稍微向下.我希望在RStudio中调整图形窗口的大小时自动进行调整.
As you can see, the letter B is not at the same distance on the x axis and it's a little down. I would like this to be adjusting automatically when I resize the graphic window in RStudio.
推荐答案
这是我过去解决该问题的方式(基于以下问题:,):
This is how I have solved that problem in the past (based on these questions: Get margin line locations (mgp) in user coordinates, Get margin line locations in log space):
line2user <- function(line, side) {
lh <- par('cin')[2] * par('cex') * par('lheight')
x_off <- diff(grconvertX(c(0, lh), 'inches', 'npc'))
y_off <- diff(grconvertY(c(0, lh), 'inches', 'npc'))
switch(side,
`1` = grconvertY(-line * y_off, 'npc', 'user'),
`2` = grconvertX(-line * x_off, 'npc', 'user'),
`3` = grconvertY(1 + line * y_off, 'npc', 'user'),
`4` = grconvertX(1 + line * x_off, 'npc', 'user'),
stop("Side must be 1, 2, 3, or 4", call.=FALSE))
}
addfiglab <- function(lab, xl = par()$mar[2], yl = par()$mar[3]) {
text(x = line2user(xl, 2), y = line2user(yl, 3),
lab, xpd = NA, font = 2, cex = 1.5, adj = c(0, 1))
}
par(mfrow = c(1, 2))
plot(0)
addfiglab("A")
plot(1000)
addfiglab("B")
这篇关于图形标签:尽管图形大小,也可以在同一位置的图形上添加文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!