Y轴创建但不可见

时间:2014-08-24 00:12:54

标签: javascript html css d3.js

我使用以下代码

创建了一个带有D3.js的简单条形图
<!DOCTYPE html>
<html>
 <head>
    <title>Bar Transition Example</title>
    <script type="text/javascript" src="http://d3js.org/d3.v3.min.js"></script>

 </head>
 <body>

<script type="text/javascript">

var margin = {top: 20, right: 20, bottom: 30, left: 60},
    width = 300 - margin.left - margin.right,
    height = 400 - margin.top - margin.bottom;

var x = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var y = d3.scale.linear()
    .range([height, 0]);

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

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

data = [{"label":"apples","value":6000},{"label":"pears","value":5000},{"label":"bananas","value":4000}]


function bars(data)
{

    x.domain(data.map(function(d) { return d.label; }));
    y.domain([0, d3.max(data, function(d) { return d.value; })]);

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

    d3.select("svg").append('g')
    .attr("class", "y axis")
    .call(yAxis)
    .append("text")
    .attr("transform", "rotate(-90)")
    .attr("y", 6)
    .attr("dy", ".90em")
    .style("text-anchor", "end");

   bars = d3.select("svg").selectAll(".bar")
    .data(data)

    //enter
    bars.enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return x(d.label); })
    .attr("width", x.rangeBand())
    .attr("y", function(d) { return y(d.value); })
    .attr("height", function(d) { return height - y(d.value); });

}


function init()
{

    //setup the svg
    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 + ")");

    bars(data)
}

init();
    </script>

 </body>
</html>

然而我的Y轴并没有像我期望的那样可视化。确实,  Y轴已创建 enter image description here

我尝试调整所有参数(包括边距变量

var margin = {top: 20, right: 20, bottom: 30, left: 60},
        width = 300 - margin.left - margin.right,
        height = 400 - margin.top - margin.bottom;

但没有效果。

1 个答案:

答案 0 :(得分:0)

您需要翻译包含轴的组:

d3.select("svg").append('g')
    .attr('transform', 'translate(' + [margin.left, margin.top] + ')')
    .attr("class", "y axis")
    .call(yAxis);

轴被绘制在SVG元素之外。您可能还想翻译另一个组。的问候,