代码之家  ›  专栏  ›  技术社区  ›  Warwick Wainwright

Sankey网络手动变色

  •  4
  • Warwick Wainwright  · 技术社区  · 7 年前

    我正在尝试使用 网络3 图书馆我有以下代码和数据:

    # Plotting the Sankey network diagram
    nodes = data.frame("name" = 
                         c("Mamalian", # Node 0
                           "Avian", # Node 1
                           "Critical", # Node 2
                           "Critical-maintained", # Node 3
                           "Endangerd", #Node 4
                           "Endangered-maintained", #Node 5
                           "Not at risk")) # Node 6
    
    links = as.data.frame(matrix(c(
      0, 2, 16, # Note the values in the final column refer to the % of breeds in each risk category
      0, 3, 2.2, 
      0, 4, 17.6, 
      0, 5, 7.0,
      0, 6, 57.2,
      1, 2, 23.9, 
      1, 3, 1.3, 
      1, 4, 24.7, 
      1, 5, 13.1,
      1, 6, 37.0),
      byrow = TRUE, ncol = 3))
    names(links) = c("source", "target", "value")
    sankeyNetwork(Links = links, Nodes = nodes,
                  Source = "source", Target = "target",
                  Value = "value", NodeID = "name",
                  fontSize= 12, nodeWidth = 30, iterations = 0)
    

    我想手动更改与每个节点相关的颜色,因为它们目前不符合我列出的危险类别。我该怎么做?

    结果如下: enter image description here

    1 回复  |  直到 7 年前
        1
  •  5
  •   CJ Yetman    7 年前

    使用 colourScale 参数设置自定义JS/D3颜色比例。(我将您姓名中的空格替换为 - 因为 d3.scaleOrdinal() 不喜欢他们)。使用示例中的数据/对象。。。。

    nodes$group <- gsub(" ", "-", nodes$name)
    
    color_scale <- 
      "d3.scaleOrdinal()
         .domain(['Mamalian', 'Avian', 'Critical', 'Critical-maintained', 
                  'Endangerd', 'Endangered-maintained', 'Not-at-risk'])
         .range(['#000', '#F00', '#0F0', '#00F', '#FF0', '#F0F', '#0FF']);
      "
    sankeyNetwork(Links = links, Nodes = nodes,
                  Source = "source", Target = "target",
                  Value = "value", NodeID = "name", 
                  fontSize= 12, nodeWidth = 30, iterations = 0,
                  NodeGroup = "group", colourScale = color_scale)