[英]Add a legend to a hierchical bar chart in D3
I have a hierarchical bar chart in D3 with two "levels" of data and I want to display a legend with two distinct items. 我在D3中有一个分层的条形图,其中包含两个“级别”的数据,我想显示带有两个不同项目的图例。
When a user clicks on a bar chart value X to go down to the next level, I want the value of X (ie a string) to appear in a legend on that new chart. 当用户单击条形图值X下降到下一个级别时,我希望X的值(即字符串)出现在该新图表的图例中。 That way, a user always knows what value/category they just clicked on. 这样,用户始终知道他们刚刚单击的值/类别。
The second part of the legend is that I want the aggregate count of all the values on a chart to show somewhere. 图例的第二部分是我希望图表上所有值的总计数显示在某处。 So if I have a chart with values of 10,15,25 I want to be able to display 50 within a legend on the chart. 因此,如果我的图表的值为10、15、25,则希望在图表的图例中显示50。
I'll asumme your are working with this: http://bl.ocks.org/mbostock/1283663 我会假设您正在使用此方法: http ://bl.ocks.org/mbostock/1283663
first add text: 首先添加文字:
var parent = svg.append("text").attr("x",-margin.left).attr("y",0)
On down function update the text: 按下功能更新文本:
parent.text("Position:"+d.name+" Value:"+d.value)
and up function: 及以上功能:
parent.text("Position:"+d.parent.name+" Value:"+d.parent.value)
Here the working code 这里的工作代码
If you don't want to show the root: 如果您不想显示根:
down function: 下降功能:
if (d.name == "flare") {
parent.text("")
} else {
parent.text("Position:"+d.name+" Value:"+d.value)
}
up function: 上功能:
if (d.parent.name == "flare") {
parent.text("")
} else {
parent.text("Position:"+d.name+" Value:"+d.parent.value)
}
To show value after each name bars, tweak function bar(d): 要在每个名称栏后面显示值,请调整功能栏(d):
bar.append("text")
.attr("x", -6)
.attr("y", barHeight / 2)
.attr("dy", ".35em")
.style("text-anchor", "end")
.text(function(d) { return d.name+" : "+d.value; }); // <-- Here made mods
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.