【问题标题】:Change the color of nodes in rCharts sankey diagram in R在R中更改rCharts sankey图中节点的颜色
【发布时间】:2015-04-14 12:03:25
【问题描述】:

我使用 rCharts 制作了桑基图。 这是我的代码示例。数据基于此 URL (http://timelyportfolio.github.io/rCharts_d3_sankey/example_build_network_sankey.html)

library(devtools)
library(rjson)
library(igraph)

devtools::install_github("ramnathv/rCharts")

library(rCharts)

 g2 <- graph.tree(40, children=4)
 V(g2)$weight = 0
 V(g2)[degree(g2,mode="out")==0]$weight <- runif(n=length(V(g2)[degree(g2,mode="out")==0]),min=0,max=100)
 E(g2)[to(V(g2)$weight>0)]$weight <- V(g2)[V(g2)$weight>0]$weight

while(max(is.na(E(g2)$weight))) {
  df <- get.data.frame(g2)
  for (i in 1:nrow(df)) {
    x = df[i,]
    if(max(df$from==x$to)) {
      E(g2)[from(x$from) & to(x$to)]$weight = sum(E(g2)[from(x$to)]$weight)
    }
  }
}

edgelistWeight <- get.data.frame(g2)
colnames(edgelistWeight) <- c("source","target","value")
edgelistWeight$source <- as.character(edgelistWeight$source)
edgelistWeight$target <- as.character(edgelistWeight$target)

sankeyPlot2 <- rCharts$new()
sankeyPlot2$setLib('http://timelyportfolio.github.io/rCharts_d3_sankey')
sankeyPlot2$set(
     data = edgelistWeight,
     nodeWidth = 15,
     nodePadding = 10,
     layout = 32,
     width = 960,
     height = 500
 )

sankeyPlot2

这是桑基图的结果。

在这种情况下,我需要更改节点的颜色。这是因为我需要突出显示一些节点,例如数字 2 和 7。所以,我想要的结果是数字 2 和 7 具有红色,而其他节点具有相同的颜色,例如灰色。

我该如何处理这个问题?

【问题讨论】:

    标签: r colors rcharts sankey-diagram


    【解决方案1】:

    我对 Javascript 不太了解,所以可能还有改进的余地,但您可以通过添加以下内容来设置颜色:

    sankeyPlot2$setTemplate(
      afterScript = "
    <script>
      d3.selectAll('#{{ chartId }} svg .node rect')
        .style('stroke', 'none')
        .style('fill', function(d){
          return('#999999')
      })
       d3.select('#{{ chartId }} svg .node:nth-child(2) rect')
        .style('fill', function(d){
          return('#ff0000')
      })
       d3.select('#{{ chartId }} svg .node:nth-child(7) rect')
        .style('fill', function(d){
          return('#ff0000')
      })
      d3.selectAll('#{{ chartId }} svg path.link')
        .style('stroke', function(d){
          if (d.source.name == 2 | d.source.name == 7) { 
            return('#ff0000'); 
          } else { 
            return('#999999');
          }
        })
    </script>
    ") 
    sankeyPlot2
    

    (similar)

    【讨论】:

    • 感谢您的帮助!我还有一个问题。我可以用你的方法设置链接的颜色吗?
    • 是的,看我的编辑。 PS:方法基本来自@timelyportfolio - stackoverflow.com/questions/25412223/…
    猜你喜欢
    • 1970-01-01
    • 2014-10-14
    • 1970-01-01
    • 1970-01-01
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多