-
Notifications
You must be signed in to change notification settings - Fork 0
/
fig_label.R
63 lines (54 loc) · 1.73 KB
/
fig_label.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
fig_label <- function(text, region="figure", pos="topleft", cex=NULL, ...) {
region <- match.arg(region, c("figure", "plot", "device"))
pos <- match.arg(pos, c("topleft", "top", "topright",
"left", "center", "right",
"bottomleft", "bottom", "bottomright"))
if(region %in% c("figure", "device")) {
ds <- dev.size("in")
# xy coordinates of device corners in user coordinates
x <- grconvertX(c(0, ds[1]), from="in", to="user")
y <- grconvertY(c(0, ds[2]), from="in", to="user")
# fragment of the device we use to plot
if(region == "figure") {
# account for the fragment of the device that
# the figure is using
fig <- par("fig")
dx <- (x[2] - x[1])
dy <- (y[2] - y[1])
x <- x[1] + dx * fig[1:2]
y <- y[1] + dy * fig[3:4]
}
}
# much simpler if in plotting region
if(region == "plot") {
u <- par("usr")
x <- u[1:2]
y <- u[3:4]
}
sw <- strwidth(text, cex=cex) * 60/100
sh <- strheight(text, cex=cex) * 60/100
x1 <- switch(pos,
topleft =x[1] + sw,
left =x[1] + sw,
bottomleft =x[1] + sw,
top =(x[1] + x[2])/2,
center =(x[1] + x[2])/2,
bottom =(x[1] + x[2])/2,
topright =x[2] - sw,
right =x[2] - sw,
bottomright =x[2] - sw)
y1 <- switch(pos,
topleft =y[2] - sh,
top =y[2] - sh,
topright =y[2] - sh,
left =(y[1] + y[2])/2,
center =(y[1] + y[2])/2,
right =(y[1] + y[2])/2,
bottomleft =y[1] + sh,
bottom =y[1] + sh,
bottomright =y[1] + sh)
old.par <- par(xpd=NA)
on.exit(par(old.par))
text(x1, y1, text, cex=cex, ...)
return(invisible(c(x,y)))
}