Search code examples
javascriptchartsscaled3.js

Defining the Coordinate System


I am just getting into javascript and d3.js. Please excuse the simple question, but I am tired of looking at this to no avail. I am sure it is glaringly obvious and simple, but why are these bars plotted from the top down and not the bottom up. I have tried to flip the values in the domain and range and tried transforming the group but nothing seems to work. Thanks.

<!DOCTYPE html>
<html>

<head>
<title>Test</title>

<script src="http://d3js.org/d3.v2.js"></script>

<style type="text/css">
    .background
    {
        background-color:Gray;
        border:solid 1px black
    }

    #container
        { 
             margin:auto;
         width:700;
    }

    body
        {
             margin:0px;
         padding:0px;
    }   

</style>
</head>

<body>
<div id="container"></div>


<script type="text/javascript">
    var data = {};

    data.distance = [3.17, 2.6, 3.08, 3.12, 3.14, 3.16, 3.19, 3.24, 3.21, 4.51, 3.18, 3.16,      3, 3.2, 3.07, 3.16, 3, 0.01, 2, 3.32, 3.33, 3, 3, 5, 3.41, 3.05, 3.01, 5, 5.03, 5, 1.68, 3, 3, 1.93, 1.96, 6.08, 4.27, 4.86, 3, 3, 2.51, 3.97, 2.87, 4, 4, 7.94, 6.64, 4, 4.03, 0.25, 2.64, 8.09, 1.96, 4.64, 5.48, 5.54, 7, 4, 4]

    var y = d3.scale.linear()
        .domain([0,d3.max(data.distance)])
        .range([0,250]);

    var chart = d3.select("div")
        .append("svg")
            .attr("class","background")
            .attr("width",10*data.distance.length)
            .attr("height",350)
        .append("g")

        chart.selectAll("rect")
            .data(data.distance)
            .enter()
                .append("rect")
                .attr("fill", "white")
                .attr("stroke","black")
                .attr("width", 10) 
                .attr("height",y)  
                .attr("x",function(d,i){return i *10});
</script>
</body>

Solution

  • If you add both y and height and you can then calculate the bar to start from the bottom:

    .attr("height", 350)  
    .attr("y", function(d) { return 350-d; })