From dda0dea5a98f5c45723fc3ff47e6e5382d84cb4a Mon Sep 17 00:00:00 2001 From: bburns632 Date: Sun, 15 Nov 2026 21:43:11 -0600 Subject: [PATCH] feat: add "Size by" dropdown to resize network nodes by a metric (#169) Network visualizations get a dropdown next to "Select by id" that resizes nodes by any numeric column of the nodes table. Node area is proportional to the value (radius 10-50). The default, "none", keeps uniform sizing. Missing/non-finite values and constant columns keep the default size. Sizes are precomputed in R and applied client-side via htmlwidgets::onRender, so htmlwidgets is added to Imports (already a visNetwork dependency). Co-Authored-By: Claude Opus 5.5 --- DESCRIPTION | 1 + NAMESPACE | 1 + NEWS.md | 1 + R/AbstractGraphReporter.R | 124 +++++++++++++++++++++++++++++++++ tests/testthat/test-plotting.R | 40 +++++++++++ 5 files changed, 167 insertions(+) diff --git a/DESCRIPTION b/DESCRIPTION index 9c6a8984..6c258dbe 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -19,6 +19,7 @@ Imports: data.table, DT, glue, + htmlwidgets, igraph(>= 2.1), knitr, magrittr, diff --git a/NAMESPACE b/NAMESPACE index 9cfde667..26800e35 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -30,6 +30,7 @@ importFrom(glue,glue) importFrom(grDevices,colorRamp) importFrom(grDevices,colorRampPalette) importFrom(grDevices,rgb) +importFrom(htmlwidgets,onRender) importFrom(igraph,V) importFrom(igraph,betweenness) importFrom(igraph,centr_betw_tmax) diff --git a/NEWS.md b/NEWS.md index 8537b301..fcd28b06 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,6 @@ # development ## NEW FEATURES +* Network visualizations now include a "Size by" dropdown that resizes nodes by any numeric metric in the nodes table, with node area proportional to the value. The default, "none", keeps the uniform node size. RIP Ed. (#169) ## CHANGES diff --git a/R/AbstractGraphReporter.R b/R/AbstractGraphReporter.R index 651e6365..96c4980c 100644 --- a/R/AbstractGraphReporter.R +++ b/R/AbstractGraphReporter.R @@ -15,6 +15,7 @@ #' @importFrom data.table data.table copy setkeyv #' @importFrom assertthat assert_that #' @importFrom grDevices colorRamp colorRampPalette rgb +#' @importFrom htmlwidgets onRender #' @importFrom magrittr %>% #' @importFrom visNetwork visNetwork visIgraphLayout visEdges visOptions # visGroups visLegend @@ -376,6 +377,11 @@ AbstractGraphReporter <- R6::R6Class( ) ) + g <- private$add_node_size_selector( + g = g + , plotDTnodes = plotDTnodes + ) + if (colorByGroup) { # Add group definitions @@ -412,6 +418,37 @@ AbstractGraphReporter <- R6::R6Class( return(g) }, + # Adds a dropdown to the graph viz that resizes nodes by a numeric + # column of the nodes table. Defaults to uniform node size. + add_node_size_selector = function(g, plotDTnodes) { + + sizeFields <- Filter( + f = function(colName) {is.numeric(self$nodes[[colName]])} + , x = names(self$nodes) + ) + + if (length(sizeFields) == 0) { + return(g) + } + + nodeSizes <- lapply( + X = sizeFields + , FUN = function(colName) {.scaleNodeSizes(plotDTnodes[[colName]])} + ) + names(nodeSizes) <- sizeFields + + g <- htmlwidgets::onRender( + x = g + , jsCode = .nodeSizeSelectorJS + , data = list( + ids = plotDTnodes[['id']] + , sizes = nodeSizes + ) + ) + + return(g) + }, + # Function to reset cached graph_viz reset_graph_viz = function() { log_info('Resetting cached graph_viz...') @@ -433,3 +470,90 @@ AbstractGraphReporter <- R6::R6Class( .igraphAvailableLayouts <- function() { return(grep("^layout_\\S", getNamespaceExports("igraph"), value = TRUE)) } + +# [title] Scale Values to Node Sizes +# [name] .scaleNodeSizes +# [description] Maps numeric values onto node radii so that node area is +# proportional to the value's position within the observed range. Missing +# and non-finite values, or a column with no spread, return NA, which +# leaves those nodes at the default size. +# [param] values a numeric vector +# [param] minSize radius for the smallest value +# [param] maxSize radius for the largest value +# [return] a numeric vector of node sizes, the same length as values +.scaleNodeSizes <- function(values, minSize = 10, maxSize = 50) { + values <- as.numeric(values) + sizes <- rep(NA_real_, length(values)) + isFinite <- is.finite(values) + + if (!any(isFinite)) { + return(sizes) + } + + valRange <- range(values[isFinite]) + if (valRange[1] == valRange[2]) { + return(sizes) + } + + scaled <- (values[isFinite] - valRange[1]) / (valRange[2] - valRange[1]) + sizes[isFinite] <- sqrt(minSize^2 + scaled * (maxSize^2 - minSize^2)) + return(sizes) +} + +# JavaScript passed to htmlwidgets::onRender() for the node size dropdown. +# "this" is the visNetwork widget instance, and data holds node ids plus +# one array of precomputed sizes per metric. Null sizes fall back to the +# size each node had when the graph was first drawn. +.nodeSizeSelectorJS <- " +function(el, x, data) { + var network = this.network; + if (!network || !data || !data.sizes) { + return; + } + + var nodesDS = network.body.data.nodes; + var ids = [].concat(data.ids); + var defaultSizes = {}; + ids.forEach(function(id) { + var node = network.body.nodes[id]; + defaultSizes[id] = node ? node.options.size : undefined; + }); + + var select = document.createElement('select'); + select.className = 'dropdown'; + select.id = 'nodeSizeSelect' + el.id; + select.title = 'Size nodes by a metric from the table'; + select.setAttribute('style', 'width: 200px; height: 26px; margin-left: 5px;'); + + var noneOption = document.createElement('option'); + noneOption.value = ''; + noneOption.text = 'Size by: none'; + select.appendChild(noneOption); + + Object.keys(data.sizes).forEach(function(metric) { + var option = document.createElement('option'); + option.value = metric; + option.text = 'Size by: ' + metric; + select.appendChild(option); + }); + + select.onchange = function() { + var metric = select.value; + var metricSizes = metric === '' ? null : [].concat(data.sizes[metric]); + nodesDS.update(ids.map(function(id, i) { + var size = metricSizes ? metricSizes[i] : null; + return { + id: id + , size: (size === null || size === undefined) ? defaultSizes[id] : size + }; + })); + }; + + var idList = document.getElementById('nodeSelect' + el.id); + if (idList && idList.parentNode) { + idList.parentNode.insertBefore(select, idList.nextSibling); + } else { + el.insertBefore(select, el.firstChild); + } +} +" diff --git a/tests/testthat/test-plotting.R b/tests/testthat/test-plotting.R index 3efd3cdc..c7b4af59 100644 --- a/tests/testthat/test-plotting.R +++ b/tests/testthat/test-plotting.R @@ -20,3 +20,43 @@ test_that('node coloring by discrete and continuous', { expect_is(viz, "visNetwork") expect_is(viz, "htmlwidget") }) + +test_that('.scaleNodeSizes maps values to area-proportional radii', { + sizes <- pkgnet:::.scaleNodeSizes(c(0, 5, 10, NA, Inf), minSize = 10, maxSize = 50) + expect_equal(sizes[1], 10) + expect_equal(sizes[3], 50) + expect_equal(sizes[2]^2, (10^2 + 50^2) / 2) + expect_true(all(is.na(sizes[4:5]))) + + # No spread or no finite values means default sizing + expect_true(all(is.na(pkgnet:::.scaleNodeSizes(c(3, 3, 3))))) + expect_true(all(is.na(pkgnet:::.scaleNodeSizes(c(NA_real_, NA_real_))))) + expect_length(pkgnet:::.scaleNodeSizes(numeric(0)), 0) +}) + +test_that('graph_viz includes node size selector for numeric node columns', { + b <- FunctionReporter$new() + b$set_package('baseballstats' + , pkg_path = system.file('baseballstats' + , package = "pkgnet" + , lib.loc = Sys.getenv('PKGNET_TEST_LIB') + ) + ) + b$calculate_default_measures() + + viz <- b$graph_viz + renderHooks <- viz$jsHooks[['render']] + expect_length(renderHooks, 1) + + hookData <- renderHooks[[1]][['data']] + numericCols <- names(b$nodes)[vapply(b$nodes, is.numeric, logical(1))] + expect_identical(names(hookData$sizes), numericCols) + expect_true("outDegree" %in% names(hookData$sizes)) + expect_identical(hookData$ids, viz$x$nodes$id) + for (metric in names(hookData$sizes)) { + expect_length(hookData$sizes[[metric]], length(hookData$ids)) + } + + # Nodes keep their default uniform size until a metric is chosen + expect_false("size" %in% names(viz$x$nodes)) +})