在水平图表上用d3.js显示标签 [英] Displaying labels on horizontal chart with d3.js
问题描述
我使用下面的代码创建一个简单的图表与d3.js。现在假设var数据格式正确(例如[20,15,15,40,10]),水平图表显示正确,但我想在左边添加一些标签,我有点不知所措由d3.js。我试图插入一个额外的div包含标签之前每个其他div表示和显示数据,但我不明白如何或如果这是正确的方法。
结果应该类似:
I'm creating a simple chart with d3.js using the following code. Now suppose the var data is properly formatted (ex. "[20,15,15,40,10]"), the horizontal chart displays properly but I'd like to add some labels on the left and I'm a bit overwhelmed by d3.js . I was trying to insert an extra div containing the label before every other div representing and showing the data, but I can't understand how or if that's the proper way. The result should look something like:
标签1 | ======================= ======== 40%== |
Label 1 |=============================40%==|
标签2 | ================= 30% == |
Label 2 |=================30%==|
标签3 | ====== 15%== |
Label 3 |======15%==|
。酒吧显示很好,但如何在左边添加标签?这是显示栏(给定一个div,id为'chart'和适当的css)的一段脚本。
and so on. The bars display just fine, but how do I add the labels on the left ? This is the piece of script that displays the bars (given a div with id 'chart' and the proper css).
chart = d3.select('#chart')
.append('div').attr('class', 'chart')
.selectAll('div')
.data(data).enter()
.append('div')
.transition().ease('elastic')
.style('width', function(d) { return d + '%'; })
.text(function(d) { return d + '%'; });
您会发现一个工作示例此处。
You'll find a working example here . So, how do I add labels on the left of every bar so that the user knows what every bar represents ?
推荐答案
我想在每一个栏的左边添加标签,您在每个栏之前附加包含标签的< div>
的想法是合理的。为此,您首先需要为每个条追加< div>
,然后附加< div>
包含标签,最后附加一个包含栏的< div>
。我已使用 JSFiddle此处更新了您的示例,其中的Javascript代码如下(一些更改也需要CSS):
I think your idea of appending a <div>
containing a label before each bar is reasonable. To do so, you first need to append a <div>
for each bar, then append a <div>
containing the label, and finally append a <div>
containing the bars. I've updated your example with a JSFiddle here, with the Javascript code below (some changes were also required to the CSS):
// Add the div containing the whole chart
var chart = d3.select('#chart').append('div').attr('class', 'chart');
// Add one div per bar which will group together both labels and bars
var g = chart.selectAll('div')
.data([52,15,9,3,3,2,2,2,1,1]).enter()
.append('div')
// Add the labels
g.append("div")
.style("display", "inline")
.text(function(d, i){ return "Label" + i; });
// Add the bars
var bars = g.append("div")
.attr("class", "rect")
.text(function(d) { return d + '%'; });
// Execute the transition to show the bars
bars.transition()
.ease('elastic')
.style('width', function(d) { return d + '%'; })
JSFiddle输出的屏幕截图
这篇关于在水平图表上用d3.js显示标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!