2016-02-05 29 views
4

將文本放置在使用networkD3呈現的sankey圖上有什麼技巧?我希望將端點的值顯示爲文本框右側的文本。我意識到懸停在框上會顯示值,但隨着框變小,在許多情況下,如果值始終在側面可見,則描述信息會更容易。將文本值放在sankey圖的右側

這裏是一個例子;我可以通過添加值作爲標籤的一部分來進行破解,但將值顯示在圖的右側會更好。

library(networkD3) 
library(data.table) 
set.seed(1999) 
links <- data.table(
    src = rep(0:4, times=c(1,1,2,3,5)), 
    target = sample(1:11, 12, TRUE), 
    value = sample(100, 12) 
)[src < target, ] # no loops 
nodes <- data.table(name=LETTERS[1:12]) 

## Need to hover to get counts 
sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target', 
    Value='value', NodeID='name', fontSize=16) 

## Add text to label 
txt <- links[, .(total = sum(value)), by=c('target')] 
nodes[txt$target+1L, name := paste0(name, ' (', txt$total, ')')] 

## Displays the counts as part of the labels 
sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target', 
    Value='value', NodeID='name', fontSize=16, width=600, height=300) 

enter image description here

回答

2

對不起,我碰到這個剛纔跑。這對於htmlwidgets中的新功能onRender功能非常有用。我試圖通過內聯評論來解釋添加JavaScript的幾行以移動節點文本。 networkD3將這些lines中的過濾器根據寬度更改爲右側或左側的位置。我們將這個應用於所有的文本,所以它會在我們的節點矩形的右邊。

library(networkD3) 
library(data.table) 
set.seed(1999) 
links <- data.table(
    src = rep(0:4, times=c(1,1,2,3,5)), 
    target = sample(1:11, 12, TRUE), 
    value = sample(100, 12) 
)[src < target, ] # no loops 
nodes <- data.table(name=LETTERS[1:12]) 

## Need to hover to get counts 
sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target', 
       Value='value', NodeID='name', fontSize=16) 

## Add text to label 
txt <- links[, .(total = sum(value)), by=c('target')] 
nodes[txt$target+1L, name := paste0(name, ' (', txt$total, ')')] 

## Displays the counts as part of the labels 
sankeyNetwork(Links=links, Nodes=nodes, Source='src', Target='target', 
       Value='value', NodeID='name', fontSize=16, width=600, height=300) 



#################### move leaf node text right ################ 
# for this to work 
# install the newest htmlwidgets 
# devtools::install_github("ramnathv/htmlwidgets") 

library(htmlwidgets) 
# add margin left since we'll need extra room 
# if you are wondering why margin left, 
# I think we just discovered a bug 
sn <- sankeyNetwork(
    Links=links, Nodes=nodes, Source='src', Target='target', 
    Value='value', NodeID='name', fontSize=16, 
    width=600, height=300, 
    # give us so room for our newly aligned labels 
    margin = list("left"=100) 
) 
# see how it looks 
sn 

# now let's use the new htmlwidget function 
# onRender 
onRender(
    sn, 
' 
function(el,x){ 
    // select all our node text 
    var node_text = d3.select(el) 
    .selectAll(".node text") 
    //and make them match 
    //https://github.com/christophergandrud/networkD3/blob/master/inst/htmlwidgets/sankeyNetwork.js#L180-L181 
    .attr("x", 6 + x.options.nodeWidth) 
    .attr("text-anchor", "start"); 
} 
' 
) 
相關問題