From b39348748ecc05328d58388a4ccb74ac3842155c Mon Sep 17 00:00:00 2001 From: mehmetgoktug Date: Sat, 8 Aug 2026 14:14:05 +0300 Subject: [PATCH] add_mtext: new 'adj' argument to align text along the margin --- R/plot_add.R | 25 +++++++++++++++---------- man/add_mtext.Rd | 13 +++++++++++-- 2 files changed, 26 insertions(+), 12 deletions(-) diff --git a/R/plot_add.R b/R/plot_add.R index dff2cbbec..b779288bb 100644 --- a/R/plot_add.R +++ b/R/plot_add.R @@ -194,31 +194,36 @@ add_abline <- function(h=NULL, v=NULL, ...) { } -add_mtext <- function(text, side=3, line=0, ...) { +add_mtext <- function(text, side=3, line=0, adj=0.5, ...) { stopifnot(side %in% 1:4) p <- unlist(get.clip()) h <- graphics::strheight(text, units = "user", ...) + adj <- c(adj[1], 0.5) srt <- 0 - if (side==1) { - x <- mean(p[1:2]) + if (side == 1) { + x <- p[1] + adj[1] * (p[2] - p[1]) y <- p[3] - h - line * h - } else if (side==2) { - x <- p[1] -1.25 * h - line * h - y <- mean(p[3:4]) + a <- adj + } else if (side == 2) { + x <- p[1] - 1.25 * h - line * h + y <- p[3] + adj[1] * (p[4] - p[3]) srt <- 90 - } else if (side==3) { - x <- mean(p[1:2]) + a <- adj + } else if (side == 3) { + x <- p[1] + adj[1] * (p[2] - p[1]) y <- p[4] + h + line * h + a <- adj } else { x <- p[2] + 1.25 * h + line * h - y <- mean(p[3:4]) + y <- p[3] + adj[1] * (p[4] - p[3]) srt <- 270 + a <- c(1 - adj[1], adj[2]) } - text(x=x, y=y, labels=text, xpd=TRUE, srt=srt, ...) + text(x=x, y=y, labels=text, xpd=TRUE, srt=srt, adj=a, ...) } diff --git a/man/add_mtext.Rd b/man/add_mtext.Rd index 728f1e77d..ba2e493ef 100644 --- a/man/add_mtext.Rd +++ b/man/add_mtext.Rd @@ -9,13 +9,14 @@ Similar to \code{\link[graphics]{mtext}} allowing adding a text to the margins o } \usage{ -add_mtext(text, side=3, line=0, ...) +add_mtext(text, side=3, line=0, adj=0.5, ...) } \arguments{ \item{text}{character or expression vector specifying the text to be written} \item{side}{ integer indicating the margin to use (1=bottom, 2=left, 3=top, 4=right)} - \item{line}{ numeric to move the text in or outwards.} + \item{line}{ numeric to move the text in or outwards} + \item{adj}{numeric between 0 and 1 to align the text along the margin. Use 0 for left (sides 1 and 3) or bottom (sides 2 and 4), 1 for right or top, and 0.5, the default, to center it} \item{...}{arguments passed to \code{\link{text}}} } @@ -29,6 +30,14 @@ r <- rast(f) plot(r, axes=FALSE, legend=FALSE) add_box() for (i in 1:4) add_mtext("margin text", i, cex=i, col=i, line=2-i) + +# align the text along the margin +plot(r, axes=FALSE, legend=FALSE) +add_box() +for (i in 1:4) { + add_mtext("start", i, adj=0, col="blue") + add_mtext("end", i, adj=1, col="red") +} } \keyword{methods}