Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
340 views
in Technique[技术] by (71.8m points)

d3.js - Proper way to draw gridlines

Okay, I'm starting to get a little more familiar with D3 but am still a little hazy on some things. I'm now trying to draw grid lines but am realizing that I may be hacking away versus doing it correctly. I tried to add some gridlines, using a tutorial, but ended up with a lot of code that I seem to be jimmy rigging in order to get it to line up properly. I was wondering if anyone could point me to a better way of writing this...

The original code is this.

        <script type="text/javascript">

            //Width and height
            var w = 800;
            var h = 400;
            var padding = 20;
            var border=1;
            var bordercolor='black';


            var dataset = [
                            [5, 20], [480, 90], [250, 50], [100, 33], [330, 95],[-50,-100],[50,-45],
                            [410, 12], [475, 44], [25, 67], [85, 21], [220, 88],[-480, -467], [3,-90],[468,481]
                          ];

                // create scale functions
                var xScale = d3.scale.linear()
                                 .domain([d3.min(dataset, function(d) { return d[0]; }), d3.max(dataset, function(d) { return d[0]; })])
                                 .range([padding, w - padding * 2]);

            var yScale = d3.scale.linear()
                                 .domain([d3.min(dataset, function(d) { return d[0]; }), d3.max(dataset, function(d) { return d[1]; })])
                                 .range([h - padding, padding]);

                var rScale = d3.scale.linear()
                .domain(  [-100,      d3.max(dataset, function(d) { return d[1];            })]   )
                .range([2,5]);

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

            //define X axis   this is rly a function, remember, variables can hold functions in JS
                var xAxis = d3.svg.axis()
                        .scale(xScale)
                        .orient("bottom")
                        .ticks(1)
                        .tickSize(-h, 0, 0)
                        ;   //Set rough # of ticks


            //Define Y axis
                var yAxis = d3.svg.axis()
                        .scale(yScale)
                        .orient("left")
                        .ticks(1)
                        .tickSize(-w, 0, 0)
                        ;




                //create the circles
            svg.selectAll("circle")
               .data(dataset)
               .enter()
               .append("circle")
               .attr("cx", function(d) {
                    return xScale(d[0]);
               })
               .attr("cy", function(d) {
                    return yScale(d[1]);
               })
               .attr("r", 3);





  //   draw axes here
   svg.append("g")
    .attr("class", "axis") //assign "axis" class
    .attr("transform", "translate(0," + (h - padding) +")")
    .call(xAxis);



       svg.append("g")
    .attr("class", "axis") //assign "axis" class
    .attr("transform", "translate(" + padding + ",0)"       )
    .call(yAxis);
// end draw axes here
        </script>

and the code I added in the second link is here

var vis = svg.append("svg:g")
    .attr("transform", "translate(20,0)")


var rules = vis.append("svg:g").classed("rules", true)


rules.append("svg:g").classed("grid x_grid", true)
    .attr("transform", "translate(-20,"+h+")")
    .call(d3.svg.axis()
      .scale(xScale)
      .orient("bottom")
      .ticks(4)
      .tickSize(-h,0,0)
      .tickFormat("")
    )

rules.append("svg:g").classed("grid y_grid", true)
    .call(d3.svg.axis()
      .scale(yScale)
      .orient("left")
      .ticks(5)
      .tickSize(-w,0,0)
      .tickFormat("")
    )

rules.append("svg:g").classed("labels x_labels", true)
    .attr("transform", "translate(-20,"+ h +")")
    .call(d3.svg.axis()
      .scale(xScale)
      .orient("bottom")
      .ticks(4)
      .tickSize(0)
            .tickFormat("")
      // .tickFormat(d3.time.format("%Y/%m"))
    )

rules.append("svg:g").classed("labels y_labels", true)
    .call(d3.svg.axis()
      .scale(yScale)
      .orient("left")
      .ticks(5)
      .tickSubdivide(1)
      .tickSize(0, 0, 0)
            .tickFormat("")
    )

Again, really appreciate any help

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Assuming that you have Mike Bostock's standard margins defined and you have defined a linear scale for the y-axis the following code will create horizontal gridlines without using tickSize().

svg.selectAll("line.horizontalGrid").data(yScale.ticks(4)).enter()
    .append("line")
        .attr(
        {
            "class":"horizontalGrid",
            "x1" : margin.right,
            "x2" : width,
            "y1" : function(d){ return yScale(d);},
            "y2" : function(d){ return yScale(d);},
            "fill" : "none",
            "shape-rendering" : "crispEdges",
            "stroke" : "black",
            "stroke-width" : "1px"
        });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...