2

在绘制条形图时,我正在尝试使用http://bl.ocks.org/mbostock/3019563中描述的边距约定。但是,条形图与 x 轴不对齐,如您在此基本示例中所见:http: //bl.ocks.org/kyrre/bbd29f225173825797e3。我究竟做错了什么?

var data = [
            {x: "Differential Geometry", y: 10},
            {x: "Statistical Physics",   y: 5},
            {x: "Music", y: 3}
           ]


var margin = {top: 20, right: 10, bottom: 20, left: 50};

var width = 500 - margin.left - margin.right;
var height = 320 - margin.top - margin.bottom;

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

var x = d3.scale.ordinal()
          .domain(_.map(data, function(d) { return d.x;}))
          .rangeRoundBands([0, width], 0.10);

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

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



var svg = d3.select("body")
            .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 rect = svg.selectAll("rect")
              .data(data)
              .enter()
              .append("rect")
              .attr("x", function(d) {
                    return x(d.x);
              })
              .attr("y", 0)
              .attr("height", function(d) {
                  return y(d.y);
              })
              .attr("fill", function(d) { return "blue";})
              .attr("width", 20);

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

svg.append("g")
   .attr("class", "y axis")
   .attr("transform", "translate(0,0)")
   .call(yAxis);
4

1 回答 1

5

坐标从顶部开始计算y(即 0 位于图像顶部)。如果您设置y为总负高度,它应该可以工作。

.attr("y", function(d) { return (height - y(d.y)); })
于 2013-03-22T16:02:01.883 回答