pic*_*ick 8 r sankey-diagram networkd3
有没有把文字放在使用networkD3渲染的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)
Run Code Online (Sandbox Code Playgroud)
对不起,我刚刚遇到过这个问题.这对于新onRender功能来说非常有用htmlwidgets.我尝试在内联注释来解释添加JavaScript的几行来移动节点文本. networkD3这些行中的过滤器可根据宽度将放置更改为向右或向左.我们将它应用于所有文本,因此它将位于节点矩形的右侧.
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");
}
'
)
Run Code Online (Sandbox Code Playgroud)