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}
0 commit comments