10

我正在 d3.js 中构建一个带有序数 x 轴的条形图,其刻度应该用文本标记图表。谁能解释序数比例如何“映射” x 对应的条形位置?具体来说,如果我想将带有文本值数组的 x 刻度标签指定给条形图中的相应条形。

目前我将域设置如下:

    var labels = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"];
    var xScale = d3.scale.ordinal()
                .domain(labels)

但是,1-19 的值显示在文本标签之后。

正如在这个小提琴中看到的:

http://jsfiddle.net/chartguy/FbqjD/

相关小提琴源代码:

//Width and height
            var margin = {top: 20, right: 20, bottom: 30, left: 40};           
            var width = 600 - margin.left - margin.right;
            var height= 500-margin.top -margin.bottom;
            var w = width;
            var h = height;


            var dataset = [ 5, 10, 13, 19, 21, 25, 22, 18, 15, 13,
                            11, 12, 15, 20, 18, 17, 16, 18, 23, 25 ];

            var labels = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t"];
            var xScale = d3.scale.ordinal()
            .domain(labels)
                            .rangeRoundBands([margin.left, width], 0.05);
            var xAxis = d3.svg.axis().scale(xScale).orient("bottom");


            var yScale = d3.scale.linear()
                            .domain([0, d3.max(dataset)])
                            .range([h,0]);


            //Create SVG element
            var svg = d3.select("body")
                        .append("svg")
                        .attr("width", w)
                        .attr("height", h);

            //Create bars
            svg.selectAll("rect")
               .data(dataset)
               .enter()
               .append("rect")
               .attr("x", function(d, i) {
                    return xScale(i);
               })
               .attr("y", function(d) {
                    return yScale(d);
               })
               .attr("width", xScale.rangeBand())
               .attr("height", function(d) {
                    return h - yScale(d);
               })
               .attr("fill", function(d) {
                    return "rgb(0, 0, 0)";
               });

            svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + 0 + ")")
      .call(xAxis);

            //Create labels
            svg.selectAll("text")
               .data(dataset)
               .enter()
               .append("text")
               .text(function(d) {
                    return d;
               })
               .attr("x", function(d, i) {
                    return xScale(i) + xScale.rangeBand() / 2;
               })
               .attr("y", function(d) {
                    return h - yScale(d) + 14;
               });
4

1 回答 1

15

您可以使用显式设置序数轴的刻度值d3.svg.axis().tickValues(*array*)

但这是一种奇怪的方法,因为它危险地分离了您的键和值,这意味着您必须小心手动对齐刻度并确保您的数据正确对应。它有助于将键和值分组到单个对象中,然后使用以下格式:

       axis.domain(array.map(function (d) { return d.value; }))

映射您的轴域。

我已经修改了您的数据并以我认为更d3 的方式进行操作。(另请注意,我做了一些其他更改只是为了好玩,即改进边距并清理轴对齐等)

于 2013-06-21T03:05:43.543 回答