【发布时间】:2018-04-18 22:16:21
【问题描述】:
尝试为最新版本的 Angular 实现 D3 图表(sankey)。我关注了这个gist,但我唯一得到的是纯文本而不是图形的节点。
我发了plunker with a minimum installation 来重现这个问题
短篇小说,
我在我的组件上导入库:
import * as d3 from 'd3';
import * as d3Sankey from 'd3-sankey';
在ngOnInit 上调用了DrawChart():
ngOnInit() {
this.DrawChart();
}
实现DrawChart()函数:
private DrawChart() {
var svg = d3.select("#sankey"),
width = +svg.attr("width"),
height = +svg.attr("height");
var formatNumber = d3.format(",.0f"),
format = function (d: any) { return formatNumber(d) + " TWh"; },
color = d3.scaleOrdinal(d3.schemeCategory10);
var sankey = d3Sankey.sankey()
.nodeWidth(15)
.nodePadding(10)
.extent([[1, 1], [width - 1, height - 6]]);
var link = svg.append("g")
.attr("class", "links")
.attr("fill", "none")
.attr("stroke", "#000")
.attr("stroke-opacity", 0.2)
.selectAll("path");
var node = svg.append("g")
.attr("class", "nodes")
.attr("font-family", "sans-serif")
.attr("font-size", 10)
.selectAll("g");
d3.json("../../../assets/vendors/uk2015.json", function (error, energy: any) {
if (error) throw error;
sankey(energy);
link = link
.data(energy.links)
.enter().append("path")
.attr("d", d3Sankey.sankeyLinkHorizontal())
.attr("stroke-width", function (d: any) { return Math.max(1, d.width); });
link.append("title")
.text(function (d: any) { return d.source.name + " → " + d.target.name + "\n" + format(d.value); });
node = node
.data(energy.nodes)
.enter().append("g");
node.append("rect")
.attr("x", function (d: any) { return d.x0; })
.attr("y", function (d: any) { return d.y0; })
.attr("height", function (d: any) { return d.y1 - d.y0; })
.attr("width", function (d: any) { return d.x1 - d.x0; })
.attr("fill", function (d: any) { return color(d.name.replace(/ .*/, "")); })
.attr("stroke", "#000");
node.append("text")
.attr("x", function (d: any) { return d.x0 - 6; })
.attr("y", function (d: any) { return (d.y1 + d.y0) / 2; })
.attr("dy", "0.35em")
.attr("text-anchor", "end")
.text(function (d: any) { return d.name; })
.filter(function (d: any) { return d.x0 < width / 2; })
.attr("x", function (d: any) { return d.x1 + 6; })
.attr("text-anchor", "start");
node.append("title")
.text(function (d: any) { return d.name + "\n" + format(d.value); });
});
}
}
控制台上没有错误,也没有任何可以为我指明正确方向的东西。
编辑:我尝试从 Chrome 中的代码检查器复制粘贴 SVG 代码,然后在在线 SVG 查看器中呈现它,它可以工作。 Angular 似乎无法渲染它生成的 SVG。但是我该如何解决呢?
【问题讨论】:
-
嗨,我正在努力解决同样的问题,即如何将 D3 图嵌入到 Angular 6 中。我得到了 D3 图的工作(本地)版本作为 HTML 文件和 TSV 输入,但是在Angular中实现它的正确方法是什么?你的问题解决了吗?
-
@B--rian 不幸的是我没有解决它
标签: angular d3.js svg sankey-diagram