Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 15 additions & 10 deletions R/plot_add.R
Original file line number Diff line number Diff line change
Expand Up @@ -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, ...)
}


Expand Down
13 changes: 11 additions & 2 deletions man/add_mtext.Rd
Original file line number Diff line number Diff line change
Expand Up @@ -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}}}
}

Expand All @@ -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}
Expand Down
Loading