如何将Sankey图首个节点文本移至图表左侧
调整Sankey图左侧节点文本的显示位置
你当前的代码设置了sinksRight = FALSE,但networkD3没有直接参数让左侧节点文本像sinksRight = TRUE时的右侧节点那样对齐到边框左侧,不过可以通过htmlwidgets::onRender自定义D3代码来实现这个效果:
library(tidyverse) library(networkD3) library(htmlwidgets) links <- data.frame(source = c("a","b","a","a","c","c","d","e","e"), target = c("e","a","a","c","a","c","a","a","e"), value = c(453, 244,3585,1055,1027,643,1021,692,268)) # 区分同名节点的处理 links$target <- paste(links$target, " ", sep = "") nodes <- data.frame( name=c(as.character(links$source), as.character(links$target)) %>% unique) links$IDsource <- match(links$source, nodes$name) - 1 links$IDtarget <- match(links$target, nodes$name) - 1 sankey <- sankeyNetwork(Links = links, Nodes = nodes, Source = "IDsource", Target = "IDtarget", Value = "value", NodeID = "name", sinksRight = FALSE) # 添加自定义JS调整左侧文本位置 sankey <- onRender(sankey, ' function(el, x) { // 选择所有节点文本 d3.select(el).selectAll(".node text") .each(function(d) { // 判断是否是最左侧的节点 if (d.x === 0) { // 把文本移到节点左侧,可根据需要调整x偏移量 d3.select(this).attr("x", -10) // 设置文本右对齐,紧贴节点 .attr("text-anchor", "end"); } }); } ') # 查看调整后的效果 sankey
代码说明
- 借助
onRender注入自定义D3逻辑,直接操作Sankey图的DOM元素 - 对x坐标为0的最左侧节点文本,修改其x偏移量(示例中设为-10,可根据实际显示需求调整),同时将文本对齐方式设为
end(右对齐),让文本紧贴节点左侧显示,和sinksRight = TRUE时右侧节点文本的显示效果形成对应
内容的提问来源于stack exchange,提问作者Kevin Li
相关产品推荐
相关产品推荐

