Skip to content

Commit

Permalink
equivalent of @kippjohnson's scale2 function from PR #32
Browse files Browse the repository at this point in the history
  • Loading branch information
briatte committed Jun 29, 2019
1 parent 7037555 commit 43a7114
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 27 deletions.
16 changes: 3 additions & 13 deletions R/fortify-igraph.R
Expand Up @@ -37,19 +37,9 @@ fortify.igraph <- function(model, layout = igraph::nicely(),
nodes = data.frame(nodes)
names(nodes) = c("x", "y")

# rescale coordinates if needed (discussed in PR #32)
if (length(unique(nodes$x)) > 1) {
nodes$x <- as.vector(scale(nodes$x, center = min(nodes$x),
scale = diff(range(nodes$x))))
} else {
nodes$x <- 0.5 # constant `x` coordinate
}
if (length(unique(nodes$y)) > 1) {
nodes$y <- as.vector(scale(nodes$y, center = min(nodes$y),
scale = diff(range(nodes$y))))
} else {
nodes$y <- 0.5 # constant `y` coordinate
}
# rescale coordinates
nodes$x <- scale_safely(nodes$x)
nodes$y <- scale_safely(nodes$y)

# import vertex attributes
if (length(igraph::list.vertex.attributes(x))) {
Expand Down
18 changes: 4 additions & 14 deletions R/fortify-network.R
Expand Up @@ -125,20 +125,10 @@ fortify.network <- function(model, data = NULL,
nodes = data.frame(nodes)
names(nodes) = c("x", "y")

# rescale coordinates if needed (discussed in PR #32)
if (length(unique(nodes$x)) > 1) {
nodes$x <- as.vector(scale(nodes$x, center = min(nodes$x),
scale = diff(range(nodes$x))))
} else {
nodes$x <- 0.5 # constant `x` coordinate
}
if (length(unique(nodes$y)) > 1) {
nodes$y <- as.vector(scale(nodes$y, center = min(nodes$y),
scale = diff(range(nodes$y))))
} else {
nodes$y <- 0.5 # constant `y` coordinate
}

# rescale coordinates
nodes$x <- scale_safely(nodes$x)
nodes$y <- scale_safely(nodes$y)

# import vertex attributes
for (y in network::list.vertex.attributes(x)) {
nodes = cbind(nodes, network::get.vertex.attribute(x, y))
Expand Down
16 changes: 16 additions & 0 deletions R/utilities.R
Expand Up @@ -35,3 +35,19 @@ theme_facet <- function(base_size = 12, base_family = "", ...) {
...
)
}

#' Rescale `x` to (0, 1), except if `x` is constant
#'
#' Discussed in PR #32.
#' @param x a vector to rescale
#' @param scale the scale on which to rescale the vector
#' @return The rescaled vector, coerced to a vector if necessary.
#' @author Kipp Johnson
scale_safely <- function(x, scale = diff(range(x))) {
if (!scale) {
x <- rep(0.5, length.out = length(x))
} else {
x <- base::scale(x, center = min(x), scale = scale)
}
as.vector(x)
}

0 comments on commit 43a7114

Please sign in to comment.