[英]Change the color of nodes in rCharts sankey diagram in R
我使用rCharts制作了sankey圖表。 這是我的代碼示例。 數據基於此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
這是sankey圖的結果。
在這種情況下,我需要更改節點的顏色。 這是因為我需要突出顯示一些節點,例如數字2和7.因此,我想要的結果是數字2和7具有紅色而其他節點具有相同的顏色,例如灰色。
我該如何處理這個問題?
我對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
( 相似 )
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.