D3直方图,不能在轴内得到条形

时间:2015-08-06 08:38:54

标签: d3.js histogram

我试图让用户从不同的数据集中绘制直方图。用户将能够输入应显示的条数。

我的问题是其中一个条形结束于我的x轴之外。

这是JSFiddle with the problem

我错过了什么?

我认为问题可能出在这个代码周围:

var bar = svg.selectAll(".bar")
        .data(data)
      .enter().append("g")
        .attr("class", "bar")
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.append("rect")
        .attr("x", 1)
        .attr("width", width/data.length)
        .attr("height", function(d) { return height - y(d.y); });

1 个答案:

答案 0 :(得分:2)

<强>更新

这应该可以胜任:https://jsfiddle.net/t4ho787f/11/

$(document).ready(function () {
    var values = [79.86, 59.57, 39.64, 49.08, 21.34, 17.05, 30.8, 3.63, 4.71, 9.88, 67.55, 71.01, 60.3, 50.95, 60.37, 48.14, 51.9, 16.91, 3.52, 67.98];

    var rawData2 = [17000, 30000, 25000, 22000, 25000, 20000, 25000, 35000, 20000, 20000, 18000, 15000];

    var userTicks = 20;

console.log("Histogram plot goes here")

    var margin = {top: 20, right: 40, bottom: 40, left: 60};
    var width = document.getElementsByClassName("canvas-0")[0].clientWidth - margin.left - margin.right;
    var height = document.getElementsByClassName("canvas-0")[0].clientHeight - margin.top - margin.bottom;

    var x = d3.scale.linear()
    .domain([d3.min(values), d3.max(values)])
    .range([0, width]);

    var data = d3.layout.histogram()
        .bins(x.ticks(userTicks))
        (values);        

    var y = d3.scale.linear()
        .domain([0, d3.max(data, function(d) { return d.y; })])
        .range([height, 0]);

    var xAxis = d3.svg.axis()
        .scale(x)
        .orient("bottom")
        .ticks(userTicks);

    var yAxis = d3.svg.axis()
        .scale(y)
        .orient("left");


    var svg = d3.select(".canvas-0").append("svg")
        .attr("width", width + margin.left + margin.right)
        .attr("height", height + margin.top + margin.bottom)
        .append("g")
            .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


    var bar = svg.selectAll(".bar")
        .data(data)
      .enter().append("g")
        .attr("class", "bar")
        .attr("transform", function(d) { return "translate(" + x(d.x) + "," + y(d.y) + ")"; });

    bar.append("rect")
        .attr("x", 1)
//        .attr("width", function (d) { return x(d.x); })
        .attr("width", x(data[0].dx) - 1)
        .attr("height", function(d) { return height - y(d.y); });

    bar.append("text")
        .attr("dy", ".75em")
        .attr("y", 6)
        .attr("x", x(data[0].dx) / 2)
        .attr("text-anchor", "middle")
        .text(function(d) { return d.y; });

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

    svg.append("g")
        .attr("class", "y axis")
        .call(yAxis);


});