本文介绍了在sankey图中为节点之间的链接涂上颜色:networkD3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找帮助为sankey图中的节点之间的链接着色的颜色.我正在R中使用networkD3包来创建绘图.这是我想要实现的一个非常简单的示例:

I am looking for help colouring the links between nodes in a sankey plot. I am using the networkD3 package in R to create the plot. Here is a very simple example of what I'd like to achieve:

library(networkD3)
nodes <- c("a", "b", "c")
source <- c(0, 0)
target <- c(1, 2)
value <- c(5, 5)
cbind(source, target, value) -> links
as.data.frame(links) -> links
as.data.frame(nodes) -> nodes
sankeyNetwork(Links=links, Nodes=nodes, Source="source",
              Target="target", Value="value")

上面的代码创建了一个简单的sankey图,该链接具有从"a"到2个节点"b""c"的链接.我想做的只是为每个链接(而不是节点)涂上不同的颜色.例如,a-> b将为绿色,而a-> c将为黄色.我尝试遵循其他使用d3.scaleOrdinal()操纵色标的示例,但是我没有任何运气.该图要么不渲染,要么始终保持灰色.

The above code creates a simple sankey diagram with links to 2 nodes, "b" and "c", from "a". What I'd like to do is simply colour each link, not node, a different colour. For example, a->b would be green, and a->c would be yellow. I have tried to follow other examples which manipulate the colour scale using d3.scaleOrdinal() but I have not had any luck. The plot either doesn't render, or remains grey throughout.

推荐答案

library(networkD3)
nodes<-c("a","b","c")
source<-c(0,0)
target<-c(1,2)
value<-c(5,5)
cbind(source,target,value)->links
as.data.frame(links)->links
as.data.frame(nodes)->nodes

links$group <- "blue"
my_color <- 'd3.scaleOrdinal() .domain(["blue"]) .range(["blue"])'

sankeyNetwork(Links = links,Nodes = nodes,Source = "source",Target =
                "target",Value = "value",  colourScale=my_color, LinkGroup="group")

您需要在链接中创建一个新列,分别使用d3.scaleOrdinal和要命名的颜色命名要绘制的链接和地图.最后,将那些传递给sankeyNetwork.上面的示例会将所有链接涂成蓝色

You need to create a new column in your links naming the links you want to paint and the map using d3.scaleOrdinal each name with a color. Finally, pass those to sankeyNetwork.The example above will paint all links as blue

library(networkD3)
nodes<-c("a","b","c")
source<-c(0,0)
target<-c(1,2)
value<-c(5,5)
cbind(source,target,value)->links
as.data.frame(links)->links
as.data.frame(nodes)->nodes


links$group[1] <- "blue"
links$group[2] <- "green"
my_color <- 'd3.scaleOrdinal() .domain(["blue", "green"]) .range(["blue", "green"])'

sankeyNetwork(Links = links,Nodes = nodes,Source = "source",Target =
                "target",Value = "value",  colourScale=my_color, LinkGroup="group")

这将是蓝色和绿色

在此处查看更多信息: https://www.r-graph-gallery.com/322-custom-colours-in-sankey-diagram/

See more here: https://www.r-graph-gallery.com/322-custom-colours-in-sankey-diagram/

这篇关于在sankey图中为节点之间的链接涂上颜色:networkD3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 19:42