Skip to content

Commit 1aeab2e

Browse files
committed
default 'len' arg; more tests & validity checks
1 parent 7a368bd commit 1aeab2e

3 files changed

Lines changed: 25 additions & 14 deletions

File tree

R/scalebar.R

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -27,11 +27,14 @@
2727
#' @importFrom ggplot2 annotate
2828
#' @importFrom methods is
2929
#' @export
30-
scalebar <- function(x, len, col="red", lwd=1, xrel=0.05, yrel=0.05) {
30+
scalebar <- function(x, len=NULL, col="red", lwd=1, xrel=0.05, yrel=0.05) {
3131
# validity
3232
if (!is(x, "SpatialDataArray"))
3333
stop("'x' should be a 'SpatialDataArray' object, i.e., an",
3434
" image or label element from a 'SpatialData' object")
35+
ok <- \(x) is.numeric(x) && is.finite(x) && length(x) == 1
36+
if (!is.null(len)) stopifnot(ok(len), len > 0)
37+
stopifnot(ok(xrel), ok(yrel))
3538

3639
xi <- which(axes(x, "name") == "x")
3740
unit <- axes(x)[[xi]]$unit
@@ -42,6 +45,7 @@ scalebar <- function(x, len, col="red", lwd=1, xrel=0.05, yrel=0.05) {
4245
unit <- .unit_map[unit]
4346

4447
wh <- .get_wh(x)
48+
if (is.null(len)) len <- 0.05*diff(wh$w)
4549
if (xrel <= 0.5) {
4650
xmin <- diff(wh$w) * xrel + wh$w[1]
4751
xmax <- diff(wh$w) * xrel + wh$w[1] + len
@@ -58,7 +62,7 @@ scalebar <- function(x, len, col="red", lwd=1, xrel=0.05, yrel=0.05) {
5862
text <- annotate(
5963
geom="text",
6064
x=(xmin+xmax)/2, y=y,
61-
color=col, label=paste0(len, unit),
62-
vjust=ifelse(yrel > 0.5, 1.5, -0.5))
65+
vjust=ifelse(yrel > 0.5, 1.5, -0.5),
66+
color=col, label=paste0(round(len, 1), unit))
6367
return(list(line, text))
6468
}

man/scalebar.Rd

Lines changed: 2 additions & 10 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

tests/testthat/test-scalebar.R

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,22 @@ test_that("scalebar()", {
2121
y <- set_unit(image(x), "y")
2222
expect_error(scalebar(image(y), 1))
2323

24-
# valid specification
24+
# invalid arguments
2525
y <- set_unit(image(x))
26+
v <- c(c(1,1), Inf, TRUE, "")
27+
for (. in v) {
28+
expect_error(scalebar(y, len=.))
29+
expect_error(scalebar(y, len=1, xrel=.))
30+
expect_error(scalebar(y, len=1, yrel=.))
31+
}
32+
33+
# default 'len'
34+
expect_silent(l <- scalebar(y, len=NULL))
35+
p <- ggplot() + l
36+
df <- layer_data(p, 1)
37+
expect_equal(df$xend-df$x, 0.05*dim(y)[3])
38+
39+
# valid arguments
2640
l <- scalebar(y,
2741
len=len <- 5.1234,
2842
xrel=xrel <- 0.05,
@@ -42,4 +56,5 @@ test_that("scalebar()", {
4256
expect_equal(df$xend, dim(y)[3]*xrel+len)
4357
expect_equal(df$y, dim(y)[2]*(1-yrel))
4458
expect_equal(df$yend, df$y)
59+
4560
})

0 commit comments

Comments
 (0)