-
-
Save nemochina2008/3fd36f995d91273f6c45092cf13ae6ab to your computer and use it in GitHub Desktop.
R function to draw figure labels in base plots
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
## from: https://logfc.wordpress.com/2017/03/15/adding-figure-labels-a-b-c-in-the-top-left-corner-of-the-plotting-region/ | |
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))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment