2015-02-13 14 views
6

Ho creato il diagramma di sankey usando rCharts. Ecco l'esempio del mio codice. I dati si basano su questo URL (http://timelyportfolio.github.io/rCharts_d3_sankey/example_build_network_sankey.html)Modificare il colore dei nodi nel diagramma di sankey rCharts in R

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 

Questo è il risultato di diagramma di Sankey. sankey diagram

In questo caso, ho bisogno di cambiare il colore dei nodi. Questo perché ho bisogno di evidenziare alcuni nodi come il numero 2 e 7. Quindi, il risultato che voglio è il numero 2 e 7 hanno il colore rosso e gli altri nodi hanno lo stesso colore come il grigio.

Come posso gestire questo problema?

risposta

7

io non so molto di Javascript, quindi ci può essere spazio per migliorare, ma è possibile impostare i colori aggiungendo questo:

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 

result

(similar)

+0

Grazie per il tuo aiuto! Ho ancora una domanda. Posso impostare i colori dei collegamenti usando il tuo metodo? – kmangyo

+0

Sì, vedere la mia modifica. PS: Il metodo è fondamentalmente da @timelyportfolio - http://stackoverflow.com/questions/25412223/adding-color-to-sankey-diagram-in-rcharts – lukeA

+0

È davvero buono! Grazie mille! – kmangyo

Problemi correlati