gpt4 book ai didi

javascript - 分层边缘捆绑 : adding parent group label

转载 作者:行者123 更新时间:2023-12-05 00:26:58 25 4
gpt4 key购买 nike

我对 HTML 和 JavaScript 很陌生。我正面临着著名的分层边缘捆绑here ,由 D3.js 库生成。

我的目标是添加一个半圆形的标签区域,以获得这样的结果:每个最终节点组都标有父节点的名称。
enter image description here

不幸的是,除了上面链接中提供的代码之外,我还没有找到任何可以从中获得灵感的代码:我的想法是修改该代码添加一些行以生成标签。

我看到了 link有一段代码可能会奏效,但我不知道如何使用它(以及我是否在正确的方向上)

node.append("text")
.attr("dy", ".31em")
.attr("x", function(d) { return d.x < 180 === !d.children ? 6 : -6; })
.style("text-anchor", function(d) { return d.x < 180 === !d.children ? "start" : "end"; })
.attr("transform", function(d) { return "rotate(" + (d.x < 180 ? d.x - 90 : d.x + 90) + ")"; })
.text(function(d) { return d.id.substring(d.id.lastIndexOf(".") + 1); });

有人有什么建议吗?

最佳答案

基本思想是在链接周围绘制一系列弧线,并将标签向外分流弧线的宽度。
V4解决方案
来自 linked block 的 d3 v4 代码的工作改编在下面:

var flare = "https://gist.githubusercontent.com/robinmackenzie/d01d286d9ac16b474a2a43088c137d00/raw/c53c1eda18cc21636ae52dfffa3e030295916c98/flare.json";
d3.json(flare, function(err, json) {
if (err) throw err;
render(json);
});

function render(classes) {

// original code
var diameter = 960,
radius = diameter / 2,
innerRadius = radius - 120;

var cluster = d3.cluster()
.size([360, innerRadius]);

var line = d3.radialLine()
.curve(d3.curveBundle.beta(0.85))
.radius(function(d) { return d.y; })
.angle(function(d) { return d.x / 180 * Math.PI; });

var svg = d3.select("body").append("svg")
.attr("width", diameter)
.attr("height", diameter)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");

var link = svg.append("g").selectAll(".link"),
node = svg.append("g").selectAll(".node");

var root = packageHierarchy(classes)
.sum(function(d) { return d.size; });

cluster(root);

// added code -----
var arcInnerRadius = innerRadius;
var arcWidth = 30;
var arcOuterRadius = arcInnerRadius + arcWidth;

var arc = d3.arc()
.innerRadius(arcInnerRadius)
.outerRadius(arcOuterRadius)
.startAngle(function(d) { return d.st; })
.endAngle(function(d) { return d.et; });

var leafGroups = d3.nest()
.key(function(d) { return d.parent.data.name.split(".")[1]; })
.entries(root.leaves())

var arcAngles = leafGroups.map(function(group) {
return {
name: group.key,
min: d3.min(group.values, function(d) { return d.x }),
max: d3.max(group.values, function(d) { return d.x })
}
});

svg
.selectAll(".groupArc")
.data(arcAngles)
.enter()
.append("path")
.attr("id", function(d, i) { return`arc_${i}`; })
.attr("d", function(d) { return arc({ st: d.min * Math.PI / 180, et: d.max * Math.PI / 180}) }) // note use of arcWidth
.attr("fill", "steelblue");

svg
.selectAll(".arcLabel")
.data(arcAngles)
.enter()
.append("text")
.attr("x", 5) //Move the text from the start angle of the arc
.attr("dy", (d) => ((arcOuterRadius - arcInnerRadius) * 0.8)) //Move the text down
.append("textPath")
.attr("class", "arcLabel")
.attr("xlink:href", (d, i) => `#arc_${i}`)
.text((d, i) => d.name)
.style("font", `300 14px "Helvetica Neue", Helvetica, Arial, sans-serif`)
.style("fill", "#fff");

// ----------------

link = link
.data(packageImports(root.leaves()))
.enter().append("path")
.each(function(d) { d.source = d[0], d.target = d[d.length - 1]; })
.attr("class", "link")
.attr("d", line);

node = node
.data(root.leaves())
.enter().append("text")
.attr("class", "node")
.attr("dy", "0.31em")
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + 8 + arcWidth) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
.attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.text(function(d) { return d.data.key; })
.on("mouseover", mouseovered)
.on("mouseout", mouseouted);

function mouseovered(d) {
node
.each(function(n) { n.target = n.source = false; });

link
.classed("link--target", function(l) { if (l.target === d) return l.source.source = true; })
.classed("link--source", function(l) { if (l.source === d) return l.target.target = true; })
.filter(function(l) { return l.target === d || l.source === d; })
.raise();

node
.classed("node--target", function(n) { return n.target; })
.classed("node--source", function(n) { return n.source; });
}

function mouseouted(d) {
link
.classed("link--target", false)
.classed("link--source", false);

node
.classed("node--target", false)
.classed("node--source", false);
}

// Lazily construct the package hierarchy from class names.
function packageHierarchy(classes) {
var map = {};

function find(name, data) {
var node = map[name], i;
if (!node) {
node = map[name] = data || {name: name, children: []};
if (name.length) {
node.parent = find(name.substring(0, i = name.lastIndexOf(".")));
node.parent.children.push(node);
node.key = name.substring(i + 1);
}
}
return node;
}

classes.forEach(function(d) {
find(d.name, d);
});

return d3.hierarchy(map[""]);
}

// Return a list of imports for the given array of nodes.
function packageImports(nodes) {
var map = {},
imports = [];

// Compute a map from name to node.
nodes.forEach(function(d) {
map[d.data.name] = d;
});

// For each import, construct a link from the source to target node.
nodes.forEach(function(d) {
if (d.data.imports) d.data.imports.forEach(function(i) {
imports.push(map[d.data.name].path(map[i]));
});
});

return imports;
}


}
.node {
font: 300 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
fill: #bbb;
}

.node:hover {
fill: #000;
}

.link {
stroke: steelblue;
stroke-opacity: 0.4;
fill: none;
pointer-events: none;
}

.node:hover,
.node--source,
.node--target {
font-weight: 700;
}

.node--source {
fill: #2ca02c;
}

.node--target {
fill: #d62728;
}

.link--source,
.link--target {
stroke-opacity: 1;
stroke-width: 2px;
}

.link--source {
stroke: #d62728;
}

.link--target {
stroke: #2ca02c;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js"></script>

您可以看到添加了用于绘制和标记弧的离散代码块 - 计算弧生成器的开始和结束 Angular 关键位是:
  var leafGroups = d3.nest()
.key(function(d) { return d.parent.data.name.split(".")[1]; })
.entries(root.leaves())

var arcAngles = leafGroups.map(function(group) {
return {
name: group.key,
min: d3.min(group.values, function(d) { return d.x }),
max: d3.max(group.values, function(d) { return d.x })
}
});
对于 leafGroups ,嵌套函数通过键的第二项对层次结构的叶子进行分组,例如 flare.analytics.cluster = analyticsflare.vis.operator.distortion = vis .对于您需要考虑的不同数据集,这里有一个选择,例如如果叶子总是处于一致的深度;标签总是唯一的。定义“父组”可以是自上而下或自下而上的定义。
对于 arcAngles ,您只需要每个组的最小值和最大值,然后您就可以继续绘制弧线并标记它们。我从 here 中删除了一些标签这是一篇关于在 d3 中标记弧的好文章。您需要再次考虑这一点,因为如果标签对于弧来说太长,它看起来不太好 - 请参阅示例中的“显示”标签。
另一个变化在这里更进一步:
  node = node
.data(root.leaves())
.enter().append("text")
.attr("class", "node")
.attr("dy", "0.31em")
.attr("transform", function(d) { return "rotate(" + (d.x - 90) + ")translate(" + (d.y + 8 + arcWidth) + ",0)" + (d.x < 180 ? "" : "rotate(180)"); })
.attr("text-anchor", function(d) { return d.x < 180 ? "start" : "end"; })
.text(function(d) { return d.data.key; })
.on("mouseover", mouseovered)
.on("mouseout", mouseouted);
注意您需要添加 arcWidth设置 transform 时属性 - 这会将节点标签向外移动以适应弧。
V6+解决方案
Observable HQ 中有更新版本的分层边缘捆绑使用 d3 v6(以及 Mike Bostok)的页面。我们可以添加类似的代码来识别组,获取 Angular 最小值/最大值并将标签向外推一点以适应弧线。

const flare = "https://gist.githubusercontent.com/robinmackenzie/d01d286d9ac16b474a2a43088c137d00/raw/c53c1eda18cc21636ae52dfffa3e030295916c98/flare.json";
const colorin = "#00f";
const colorout = "#f00";
const colornone = "#ccc";
const width = 960;
const radius = width / 2;

d3.json(flare).then(json => render(json));

function render(data) {

const line = d3.lineRadial()
.curve(d3.curveBundle.beta(0.85))
.radius(d => d.y)
.angle(d => d.x);

const tree = d3.cluster()
.size([2 * Math.PI, radius - 100]);

const root = tree(bilink(d3.hierarchy(hierarchy(data))
.sort((a, b) => d3.ascending(a.height, b.height) || d3.ascending(a.data.name, b.data.name))));

const svg = d3.select("body")
.append("svg")
.attr("width", width)
.attr("height", width)
.append("g")
.attr("transform", `translate(${radius},${radius})`);

// NEW CODE BELOW ----------------------------------------
// add arcs with labels
const arcInnerRadius = radius - 100;
const arcWidth = 30;
const arcOuterRadius = arcInnerRadius + arcWidth;
const arc = d3
.arc()
.innerRadius(arcInnerRadius)
.outerRadius(arcOuterRadius)
.startAngle((d) => d.start)
.endAngle((d) => d.end);

const leafGroups = d3.groups(root.leaves(), d => d.parent.data.name);
const arcAngles = leafGroups.map(g => ({
name: g[0],
start: d3.min(g[1], d => d.x),
end: d3.max(g[1], d => d.x)
}));

svg
.selectAll(".arc")
.data(arcAngles)
.enter()
.append("path")
.attr("id", (d, i) => `arc_${i}`)
.attr("d", (d) => arc({start: d.start, end: d.end}))
.attr("fill", "blue")
.attr("stroke", "blue");
svg
.selectAll(".arcLabel")
.data(arcAngles)
.enter()
.append("text")
.attr("x", 5) //Move the text from the start angle of the arc
.attr("dy", (d) => ((arcOuterRadius - arcInnerRadius) * 0.8)) //Move the text down
.append("textPath")
.attr("class", "arcLabel")
.attr("xlink:href", (d, i) => `#arc_${i}`)
.text((d, i) => ((d.end - d.start) < (6 * Math.PI / 180)) ? "" : d.name); // 6 degrees min arc length for label to apply

// --------------------------------------------------------



// add nodes
const node = svg.append("g")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g")
.data(root.leaves())
.join("g")
.attr("transform", d => `rotate(${d.x * 180 / Math.PI - 90}) translate(${d.y}, 0)`)
.append("text")
.attr("dy", "0.31em")
.attr("x", d => d.x < Math.PI ? (arcWidth + 5) : (arcWidth + 5) * -1) // note use of arcWidth
.attr("text-anchor", d => d.x < Math.PI ? "start" : "end")
.attr("transform", d => d.x >= Math.PI ? "rotate(180)" : null)
.text(d => d.data.name)
.each(function(d) { d.text = this; })
.on("mouseover", overed)
.on("mouseout", outed)
.call(text => text.append("title").text(d => `${id(d)} ${d.outgoing.length} outgoing ${d.incoming.length} incoming`));

// add edges
const link = svg.append("g")
.attr("stroke", colornone)
.attr("fill", "none")
.selectAll("path")
.data(root.leaves().flatMap(leaf => leaf.outgoing))
.join("path")
.style("mix-blend-mode", "multiply")
.attr("d", ([i, o]) => line(i.path(o)))
.each(function(d) { d.path = this; });

function overed(event, d) {
link.style("mix-blend-mode", null);
d3.select(this).attr("font-weight", "bold");
d3.selectAll(d.incoming.map(d => d.path)).attr("stroke", colorin).raise();
d3.selectAll(d.incoming.map(([d]) => d.text)).attr("fill", colorin).attr("font-weight", "bold");
d3.selectAll(d.outgoing.map(d => d.path)).attr("stroke", colorout).raise();
d3.selectAll(d.outgoing.map(([, d]) => d.text)).attr("fill", colorout).attr("font-weight", "bold");
}

function outed(event, d) {
link.style("mix-blend-mode", "multiply");
d3.select(this).attr("font-weight", null);
d3.selectAll(d.incoming.map(d => d.path)).attr("stroke", null);
d3.selectAll(d.incoming.map(([d]) => d.text)).attr("fill", null).attr("font-weight", null);
d3.selectAll(d.outgoing.map(d => d.path)).attr("stroke", null);
d3.selectAll(d.outgoing.map(([, d]) => d.text)).attr("fill", null).attr("font-weight", null);
}

function id(node) {
return `${node.parent ? id(node.parent) + "." : ""}${node.data.name}`;
}

function bilink(root) {
const map = new Map(root.leaves().map(d => [id(d), d]));
for (const d of root.leaves()) d.incoming = [], d.outgoing = d.data.imports.map(i => [d, map.get(i)]);
for (const d of root.leaves()) for (const o of d.outgoing) o[1].incoming.push(o);
return root;
}

function hierarchy(data, delimiter = ".") {
let root;
const map = new Map;
data.forEach(function find(data) {
const {name} = data;
if (map.has(name)) return map.get(name);
const i = name.lastIndexOf(delimiter);
map.set(name, data);
if (i >= 0) {
find({name: name.substring(0, i), children: []}).children.push(data);
data.name = name.substring(i + 1);
} else {
root = data;
}
return data;
});
return root;
}

}
.node {
font: 300 11px "Helvetica Neue", Helvetica, Arial, sans-serif;
fill: #fff;
}

.arcLabel {
font: 300 14px "Helvetica Neue", Helvetica, Arial, sans-serif;
fill: #fff;
}

.node:hover {
fill: #000;
}

.link {
stroke: steelblue;
stroke-opacity: 0.4;
fill: none;
pointer-events: none;
}

.node:hover,
.node--source,
.node--target {
font-weight: 700;
}

.node--source {
fill: #2ca02c;
}

.node--target {
fill: #d62728;
}

.link--source,
.link--target {
stroke-opacity: 1;
stroke-width: 2px;
}

.link--source {
stroke: #d62728;
}

.link--target {
stroke: #2ca02c;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/6.0.0/d3.min.js"></script>

需要注意的一些差异:
  • hierarchy功能不同于 packageHierarchy原始 block 中的函数 - 似乎我们不再拥有层次结构的完整路径,因此 flare.vis.data.EdgeSprite 存在歧义对比 flare.data.DataField即两个叶子可以在层次结构的不同分支中具有相同的“父级”。
  • 我已经修复了输入以适应它,但它改变了“父组”的识别方式,即原始组中的自下而上与自上而下。
  • nest已消失,因此您可以使用 groups而是
  • v4 似乎有以度为单位的 Angular 定义的对象,但在 v6 中它们以弧度为单位 - 所以你会看到一些 * Math.PI / 180在 v4 版本中而不是在 v6 中 - 但它只是度/弧度转换。
  • 对于长标签,我使用一个阈值,使得弧必须至少为 6 度长,否则标签不会放置 (.text((d, i) => ((d.end - d.start) < (6 * Math.PI / 180)) ? "" : d.name);)
  • 关于javascript - 分层边缘捆绑 : adding parent group label,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49174384/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com