简体   繁体   中英

Aligning labels to bar chart using d3.js

I'm trying to configure a bar chart but am having trouble with labeling the rect elements themselves. Here is what I have currently and the output I'm getting:

svg.selectAll("svg")
            .data(chartData)
            .enter()
            .append("text")
            .text(function (d) {
                return d.value;
            })
            .attr("x", function (d, i) {
                return i * (width / chartData.length) + (width / chartData.length / 2);
            })
            .attr("y", function (d) {
                return Math.min(450, height - (d.value * 6) + 30);
            })
            .attr("class", "bar-chart-label");

Output:

在此处输入图片说明

Notice how the ticks don't line up. What am I doing wrong? I have also tried toggling the text-anchor: middle CSS tag, and while it changes things it doesn't really solve the problem.

Thanks in advance.

EDIT: I added a jsbin example to show what I'm doing: http://jsbin.com/cugozihadi/edit?js,output .

So here is the issue. You're not adding the text to the rectangles in this case, you are adding it to the svg element directly. What you should be doing is:

  1. Create the SVG element. (I'm not sure why you are doing svg.selectAll("svg") because that selects svg inside svg...which you shouldn't do)
  2. Append tags to it (literally the group tag).
  3. Add the rectangles and the text to those groups.
  4. Add axes and other information to the chart.

Look at a very basic example here: https://bl.ocks.org/mbostock/3885304 Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM