Skip to contents


Package: RGraphSpace 1.5.8.1

# Check required version
if (packageVersion("RGraphSpace") < "1.5.8"){
  message("Need to update 'RGraphSpace' for this vignette")
  remotes::install_github("sysbiolab/RGraphSpace")
}

Overview

Node coordinates often have a physical meaning: pixels of a microscopy image, micrometers of a tissue section, or kilometers of a projected map. Normalization, however, rescales coordinates into a [0, 1] graph space, so the coordinates alone no longer tell how large the depicted area is. RGraphSpace keeps this information as a physical unit: metadata stating the physical length of one coordinate unit. The unit does not change the coordinates, and it is preserved across normalization, cropping, rotation, and other transformations.

Setting a physical unit

We use the gs_image_toy dataset, a GraphSpace object whose node coordinates are pixel indices of an embedded image (see the Mapping Graphs to Images tutorial). For this example, we assume that one image pixel corresponds to 0.5 micrometers.

library("RGraphSpace")
library("igraph")
library("ggplot2")
library("units")
library("patchwork")

# Load the toy GraphSpace object, with node
# coordinates mapping to image pixels
data("gs_image_toy")
gs <- gs_image_toy

# One coordinate unit (one pixel) is 0.5 micrometers
gs_coords_unit(gs) <- c(um = 0.5)
gs_coords_unit(gs)
#>  um 
#> 0.5

The unit is given as a single named number, whose name is the unit symbol, such as c(um = 1), or as a unit symbol alone, such as "um", which is equivalent. Metric units are built in ("nm", "um", "mm", "cm", "m" and "km"); other length units, such as miles or feet, are handled by the optional units package, which also accepts units objects as input and output.

# The same unit, as a 'units' object
gs_coords_unit(gs) <- units::set_units(0.5, "um")
gs_coords_unit(gs, as_units = TRUE)
#> 0.5 [um]

# Unit conversion is then available from 'units'
units::set_units(gs_coords_unit(gs, as_units = TRUE), "nm")
#> 500 [nm]

With a unit set, gs_coords_extent() can also return the physical size of the plotted area: before normalization, the range of the node positions.

# Width and height in plot coordinate units
gs_coords_extent(gs)
#>  width height 
#>    299    175

# Width and height in micrometers
gs_coords_extent(gs, unit = "um")
#>  width height 
#>  149.5   87.5

The nodes span 149.5 x 87.5 micrometers: 299 x 175 plot coordinate units at 0.5 micrometers per unit.

Physical units across transformations

Normalization

Next, we normalize the graph to the image space. Node coordinates now fall in [0, 1], so one coordinate unit spans the full plotted area rather than a single pixel.

gs <- normalizeGraphSpace(gs, mar = 0.1)

# Normalized width and height in coordinate units
gs_coords_extent(gs)
#>  width height 
#>      1      1

# Normalized width and height in micrometers, 
# now including the margins
gs_coords_extent(gs, unit = "um")
#>  width height 
#>    188    188

# Raw width and height are unchanged
gs_coords_extent(gs, raw = TRUE)
#>  width height 
#>    299    175

# Raw width and height in micrometers are also unchanged
gs_coords_extent(gs, raw = TRUE, unit = "um")
#>  width height 
#>  149.5   87.5

# The unit of the input coordinates is unchanged
gs_coords_unit(gs)
#>  um 
#> 0.5

Converting coordinates to physical units

With the unit argument, gs_coords() returns the coordinates in a physical unit, current or raw.

# Extract current coordinates, in normalized units
xy_norm <- gs_coords(gs)

# Extract current coordinates, in micrometers
xy_um <- gs_coords(gs, unit = "um")

# Extract raw coordinates, in micrometers
xy_raw_um <- gs_coords(gs, raw = TRUE, unit = "um")

# Distances between nodes in the normalized space
round(dist(xy_norm), 2)
#>      n1   n2   n3   n4
#> n2 0.16               
#> n3 0.23 0.37          
#> n4 0.43 0.55 0.48     
#> n5 0.63 0.80 0.49 0.45

# Distances between nodes agree, in micrometers
round(dist(xy_um), 2)
#>        n1     n2     n3     n4
#> n2  31.00                     
#> n3  43.84  69.32              
#> n4  79.90 104.16  91.14       
#> n5 118.50 149.50  92.83  83.88
round(dist(xy_raw_um), 2)
#>        n1     n2     n3     n4
#> n2  31.00                     
#> n3  43.84  69.32              
#> n4  79.90 104.16  91.14       
#> n5 118.50 149.50  92.83  83.88

Positions converted from the current coordinates are measured from the corner of the plotted area, while raw positions keep the origin of the input data. Distances, which do not depend on the origin, are identical.

Cropping

Cropping zooms into a region of the graph space and rescales it to [0, 1], so the physical size of the plotted area shrinks with the cropped region.

# Crop a region of the graph space around two of the nodes
gs_crop <- cropGraphSpace(gs, xmin = 0.3, xmax = 0.8, 
  ymin = 0.3, ymax = 0.8)

# Normalized width and height in coordinate units,
# rescaled to '[0, 1]'  
gs_coords_extent(gs_crop)
#>  width height 
#>      1      1

# Normalized width and height in micrometers,
# shrinks to the cropped area
gs_coords_extent(gs_crop, unit = "um")
#>  width height 
#>     94     94

# Raw width and height in micrometers,
# the span of the remaining nodes
gs_coords_extent(gs_crop, raw = TRUE, unit = "um")
#>  width height 
#>   56.5   56.5

Note on scale factors: when the coordinates also need a scale factor, the unit still refers to the input coordinates; see defining coordinate units.

Displaying a scale bar

annotation_gspace_scalebar() adds a horizontal scale bar to a plot, using the unit of the GraphSpace object. By default, it chooses a round length of about a fifth of the plot width, labelled in a readable unit.

The bar follows the plotted object. After cropping, the plot covers a smaller physical area, and the automatic scale bar adapts by choosing a shorter round length:

p1 <- ggplot(gs) +
    annotation_gspace_image(gs) +
    geom_edgespace() + geom_nodespace() +
    annotation_gspace_scalebar() +
    theme_gspace_coords(is_norm = TRUE) +
    labs(title = "Normalized")

p2 <- ggplot(gs_crop) +
    annotation_gspace_image(gs_crop) +
    geom_edgespace() + geom_nodespace() +
    annotation_gspace_scalebar() +
    theme_gspace_coords(is_norm = TRUE) +
    labs(title = "Cropped")

p1 + p2

Both bars span a similar part of their plots, but represent different lengths: the cropped plot spans 94 micrometers, against 188 before cropping.

Customizing the scale bar

The bar length can be set explicitly, as a named number or a units object, and the label unit with the unit argument. Position, colour, and size follow the usual ggplot2 conventions.

p <- ggplot(gs) +
  annotation_gspace_image(gs) +
  geom_edgespace() + geom_nodespace() +
  annotation_gspace_scalebar(length = c(um = 50),
    linewidth = 1.5, label.size = 4) +
  annotation_gspace_scalebar(unit = "mm", 
    colour = "black", label.size = 4,
    box = element_rect(fill = "pink"),
    position = "bottomright") +
  theme_gspace_coords(is_norm = TRUE)
p

Defining coordinate units

So far, the node coordinates of gs_image_toy were pixel indices of its embedded image: one coordinate unit was one image pixel, which we assumed to be 0.5 micrometers; since the coordinates already match the image, no scale factor was needed.

Other data can use other coordinate units, such as micrometers or pixels of a different image, so two questions define the coordinate unit of any data: how long is one coordinate unit, physically? and, if there is an image, how many image pixels fit in one coordinate unit? The answers are set with two accessors:

The unit is optional, used to draw scale bars; the scale factor is needed to align the coordinates with the embedded image, when they are not already its pixel indices. The unit can be set at any time: it always refers to the input coordinates. For real-world examples, see the Visium HD and Xenium tutorials.

Beyond microscopy

The same approach applies to maps, once node coordinates are projected into a length-based coordinate system, such as meters. See the Interoperability tutorial for an example, including when to use ggspatial::annotation_scale() instead.

Session information

#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.26.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: America/Sao_Paulo
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> 
#> other attached packages:
#> [1] patchwork_1.3.2     units_1.0-1         igraph_2.3.4       
#> [4] RGraphSpace_1.5.8.1 ggplot2_4.0.4      
#> 
#> loaded via a namespace (and not attached):
#>  [1] sass_0.5.0         generics_0.1.4     tidyr_1.3.2        class_7.3-24      
#>  [5] KernSmooth_2.23-27 lattice_0.23-1     digest_0.6.39      magrittr_2.0.5    
#>  [9] evaluate_1.0.5     grid_4.6.2         RColorBrewer_1.1-3 fastmap_1.2.0     
#> [13] jsonlite_2.0.0     Matrix_1.7-6       e1071_1.7-17       ggrastr_1.0.3     
#> [17] DBI_1.3.0          purrr_1.2.2        scales_1.4.0       textshaping_1.1.0 
#> [21] jquerylib_0.1.4    cli_3.6.6          rlang_1.3.0        tidygraph_1.3.1   
#> [25] withr_3.0.3        cachem_1.1.0       yaml_2.3.12        otel_0.3.0        
#> [29] ggbeeswarm_0.7.3   tools_4.6.2        dplyr_1.2.1        vctrs_0.7.3       
#> [33] R6_2.6.1           proxy_0.4-29       classInt_0.4-11    lifecycle_1.0.5   
#> [37] fs_2.1.0           htmlwidgets_1.6.4  vipor_0.4.7        ragg_1.5.2        
#> [41] pkgconfig_2.0.3    beeswarm_0.4.0     desc_1.4.3         pkgdown_2.2.1     
#> [45] pillar_1.11.1      bslib_0.12.0       gtable_0.3.6       glue_1.8.1        
#> [49] Rcpp_1.1.2         sf_1.1-3           systemfonts_1.3.4  xfun_0.62         
#> [53] tibble_3.3.1       tidyselect_1.2.1   rstudioapi_0.19.0  knitr_1.52        
#> [57] dichromat_2.0-1    farver_2.1.2       htmltools_0.5.9    rmarkdown_2.32    
#> [61] compiler_4.6.2     S7_1.0.0