'R - networkD3 issues
I am using networkD3 in R to display my data (sankeyNetwork function). I ran into several issues that do not seem to have solutions available.
Issue 1: If node names similar, the same color is used, even though in total, they differ e.g. if the names are 1. "one two three", 2. "one three". The names here are assigned through the NodeID. If 1. is renamed to something like "Two one three" the issue is not there anymore. Is there a way to display the names like this and have the colors assigned the way they are supposed to?
Issue 2: No decimals shown in values of links or nodes. This issue is annoying, when wanting to display percentages with decimals. If a value is below 1% (or maybe .5%), it just shows 0% and with all values it just rounds to the next full number. Is there a way to display decimals (2 or 3)? A workaround for this would be to making the numbers large by multiplying them and replace the decimal separator but for this I haven't found a full solution yet. The answer here provides a solution to replace the decimal separator in the links. However, the nodes are still displayed like before and the unit sign is removed.
Issue 3: Adding titles to node "groups" or steps. My data is designed in a way that there are three time steps with identical nodes (8 nodes in each of the 3 steps). How can I add a title above each of the steps that provides custom information about that "group" of nodes. (I suppose that NodeGroup might be something different, than what I am referring to, hence the quotes).
Solution 1:[1]
{networkD3} has a hardcoded formatting option set inside of its JavaScript. You can reset it to be whatever you want using the example answer you linked to... critically setting the format option in the .format(",.2f")
bit, where in this case the 2 means print two digits after the decimal point.
library(networkD3)
library(htmlwidgets)
nodes <- data.frame(name = c('a','b'))
links <- data.frame(source = 0, target = 1, value = 0.34)
p <- sankeyNetwork(
Links = links,
Source = "source",
Target = "target",
Value = "value",
Nodes = nodes,
NodeID = "name",
fontSize = 12,
nodeWidth = 30,
iterations = 0
)
customJS <- '
function(el,x) {
var link = d3.selectAll(".link");
var format = d3.formatLocale({"decimal": ",", "thousands": ".", "grouping": [3], "currency": ["", "\u00a0€"]}).format(",.2f");
link.select("title").select("body")
.html(function(d) { return "<pre>" + d.source.name + " \u2192 " + d.target.name +
"\\n" + format(d.value) + "<pre>"; });
}
'
onRender(p, customJS)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | CJ Yetman |