我是noob使用D3和复杂的json与这个库,我有一个问题,我需要在饼图的每个路径中添加另一个attr或图像,我不知道如何
我的json代码:
[
{"hash_chart_name" : "Chart_1", "articles" : 25, "images" : 25, "videos" : 50, "hash_link" : "pepe_1"},
{"hash_chart_name" : "Chart_2", "articles" : 25, "images" : 50, "videos" : 25, "hash_link" : "pepe_2"},
{"hash_chart_name" : "Chart_3", "articles" : 50, "images" : 25, "videos" : 25, "hash_link" : "pepe_3"},
{"hash_chart_name" : "Chart_4", "articles" : 75, "images" : 5, "videos" : 10, "hash_link" : "pepe_4"},
{"hash_chart_name" : "Chart_5", "articles" : 10, "images" : 80, "videos" : 10, "hash_link" : "pepe_5"}
]
D3代码:
var radius = 90;
var color = d3.scale.ordinal()
.range([chart_vars_object.color_1, chart_vars_object.color_2, chart_vars_object.color_3]);
var arc = d3.svg.arc()
.outerRadius(radius)
.innerRadius(radius - 50);
var pie = d3.layout.pie()
.sort(null)
.value(function(d) { return d.hash_taggeds_porcent; });
d3.json("json_hard_coded.json", function(error, data) {
color.domain(d3.keys(data[0]).filter(function(key) { return key !== "hash_chart_name"; }));
data.forEach(function(d) {
d.hash_taggeds = color.domain().map(function(name) {
//console.log({hash_taggeds_name: name, hash_taggeds_porcent: +d[name]});
return {hash_taggeds_name: name, hash_taggeds_porcent: +d[name]};
});
});
var svg = d3.select("#canvas_svg").selectAll(".pie")
.data(data)
.enter().append("svg")
.attr("class", "pie")
.attr("width", radius * 2.5)
.attr("height", radius * 2.5)
.append("g")
.attr("transform", "translate(" + radius + "," + radius + ")");
svg.selectAll(".arc")
.data(function(d) { return pie(d.hash_taggeds); })
.enter().append("path")
.attr("class", "arc")
.attr("d", arc)
//.attr("hash_link", function(d) { return d.hash_link;});
.style("fill", function(d) { return color(d.data.hash_taggeds_name); })
.style({ 'stroke': 'Black', 'stroke-width': '5px'})
.on("mouseover", function() {
d3.select(this)
.classed("active", true )
})
.on("mouseout", function() {
d3.select(this)
.classed("active", false)
});
svg.append("text")
.attr("dy", ".35em")
.style({"text-anchor":"middle", "color":"white"})
.text(function(d) { return d.hash_chart_name; });
});
好的attr:
.attr("hash_link", function(d) { return d.hash_link;});
不起作用
我该怎么办?
对不起我的英文,谢谢.-
答案 0 :(得分:0)
我同意Lars的评论,即您不应该将此属性存储在属性中,因为它可以在绑定数据中使用。您应该可以在点击处理程序中访问它,如下所示:
selection.on("click", function(el) {
console.log(el.data.hash_link);
});
也就是说,为了使其正常工作,您需要在绑定数据中使用此属性。由于您已绑定到d.hashed_tags
,因此您希望在该对象上提供此属性:
data.forEach(function(d) {
d.hash_taggeds = color.domain().map(function(name) {
return {hash_taggeds_name: name, hash_taggeds_porcent: +d[name], hash_link: d.hash_link};
});
});