Skip to content

Instantly share code, notes, and snippets.

@Pakillo
Created April 10, 2017 17:03
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save Pakillo/5712db8a54f3efb3b1583c52a2e2e270 to your computer and use it in GitHub Desktop.
Save Pakillo/5712db8a54f3efb3b1583c52a2e2e270 to your computer and use it in GitHub Desktop.
R function to draw figure labels in base plots
## 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)))
}
@BastienNguyen
Copy link

Very useful function but It seems that it did not work when using plot with log axis. Do you know how to place the text correctly when using log axis?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment