D3.js Visualization - how to add Y axis gridlines

不打扰是莪最后的温柔 提交于 2019-12-12 04:16:12

问题


I am trying to add a y gridline to a d3.js visualization I created. I have tried approaches from other posts like creating a function etc.

I found some great examples like this http://bl.ocks.org/hunzy/11110940 and this https://bl.ocks.org/d3noob/c506ac45617cf9ed39337f99f8511218.

I tried ticksize, but it didn't work (maybe because I have written out labels?).

I also tried this code, but got the error that d3.axisLeft doesn't exist.

// gridlines in y axis function
  function make_y_gridlines() {   
  return d3.axisLeft(yscale)
    .ticks(25)
    }
// add the Y gridlines
   main.append('g')     
     .attr("class", "grid")
     .call(make_y_gridlines()
        .tickSize(-width)
        .tickFormat("")
    )

Yet I cannot make it work for my graph (although it's probably super simple).

This is the code:

<!DOCTYPE html>
    <html>
       <head>
          <title>The d3 test</title>
<style>
  .chart {
   }

.main text {
         font: 10px sans-serif;  
 }

.axis line, .axis path {
   shape-rendering: crispEdges;
   stroke: black;
   fill: none;
 }

.tick line{
    opacity: 0.2;
    }

</style>
    <script type="text/javascript" src="http://mbostock.github.com/d3/d3.v2.js"></script>
  </head>
  <body>
    <div class='content'>

    </div>
    <script>
      var data = [[5,1,2],[4,2,2],[5,2,2],[3,3,1],[4,3,1],[5,3,2],[1,4,1],[5,4,2],[5,5,2],[5,6,2],[5,7,2],
      [2,8,1],[4,8,1],[5,8,2],[1,9,1],[3,9,1],[5,9,1],[1,10,2],[2,10,1],[3,10,1],[5,10,2],[1,11,3],[2,11,1],[3,11,2],[4,11,1],[5,11,1],
      [1,12,3],[5,12,5],[1,13,3],[3,13,2],[5,13,2],[1,14,1],[5,14,2],[4,15,2],[5,15,2],[3,16,1],[4,16,1],[5,16,2],[2,17,1],[5,17,2],
      [5,18,2],[5,18,2],[1,19,1],[2,19,1],[3,19,2],[5,19,1],[5,20,2],[4,21,1],[5,21,1],[1,22,1],[5,22,2],[2,23,2],[4,23,1],[5,23,2],[1,24,3],[5,24,1],
                  ];

var margin = {top: 30, right: 100, bottom: 30, left: 150}
  , width = 960 - margin.left - margin.right
  , height = 900 - margin.top - margin.bottom;

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

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

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

var color = d3.scale.category10();

var chart = d3.select('body')

.append('svg:svg')
   .attr('width', width + margin.right + margin.left)
   .attr('height', height + margin.top + margin.bottom)
   .attr('class', 'chart')

var main = chart.append('g')
   .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
   .attr('width', width)
   .attr('height', height)
   .attr('class', 'main')   

// draw the x axis
var xAxis = d3.svg.axis()
    .scale(xscale)
    .orient('bottom')
    .ticks(6)
    .tickFormat(function (d, i) {
        return ['','everyday','once a week','several times a week','1-3 times a month','less than once a month'][d];
    });


main.append('g')
  .attr('transform', 'translate(0,' + height + ')')
  .attr('class', 'main axis date')
  .call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
  .scale(yscale)
  .orient('left')
  .ticks(25)
  .tickPadding(10)
  .tickFormat(function (d, i) {
        return ['','A','B','C','D','E','F','G','H','I'
        ,'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X'
        ][d];
    });

main.append('g')
  .attr('transform', 'translate(0,0)')
  .attr('class', 'main axis date')
  .call(yAxis);

var g = main.append("svg:g"); 

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle")
      .attr("cx", function (d,i) { return xscale(d[0]); } )
      .attr("cy", function (d) { return yscale(d[1]); } )
      .attr("r", function (d) { return rscale(d[2]); } )
      .style("fill", function(d) { return color(d[2]); });
      // .attr("r", 8);


    </script>
  </body>
</html>

回答1:


Your examples use more recent versions so of d3 (v3 and v4 respectively). The documentation for version 2, which you are using, is a bit sparse now from what I can see, but the version you are using likely doesn't include the tick sizing functions you want.

If you update your d3.js version to version 3 rather than version 2, you can set your y axis ticks to stretch across plot area:

  yAxis.innerTickSize(-width)

Using your code I got this to work simply by using d3.js v3

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

Without some minor changes, using d3 v4 will break your code as there are some namespace changes: d3.scale.linear is nw d3.scaleLinear now for example.




回答2:


You're using (for whatever reason) D3 version 2. While it's advised to use a newer version, it's possible to create some gridlines, getting the position of the y axis ticks:

d3.selectAll("g.yAxis g") 
    .append("line") 
    .attr("class", "gridline")
    .attr("x1", 0) 
    .attr("y1", 0)
    .attr("x2", width)
    .attr("y2", 0);

Here is a demo with your code and D3 v2:

var data = [[5,1,2],[4,2,2],[5,2,2],[3,3,1],[4,3,1],[5,3,2],[1,4,1],[5,4,2],[5,5,2],[5,6,2],[5,7,2],
      [2,8,1],[4,8,1],[5,8,2],[1,9,1],[3,9,1],[5,9,1],[1,10,2],[2,10,1],[3,10,1],[5,10,2],[1,11,3],[2,11,1],[3,11,2],[4,11,1],[5,11,1],
      [1,12,3],[5,12,5],[1,13,3],[3,13,2],[5,13,2],[1,14,1],[5,14,2],[4,15,2],[5,15,2],[3,16,1],[4,16,1],[5,16,2],[2,17,1],[5,17,2],
      [5,18,2],[5,18,2],[1,19,1],[2,19,1],[3,19,2],[5,19,1],[5,20,2],[4,21,1],[5,21,1],[1,22,1],[5,22,2],[2,23,2],[4,23,1],[5,23,2],[1,24,3],[5,24,1],
                  ];

var margin = {top: 30, right: 100, bottom: 30, left: 150}
  , width = 960 - margin.left - margin.right
  , height = 900 - margin.top - margin.bottom;

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

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

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

var color = d3.scale.category10();

var chart = d3.select('body').append('svg:svg')
   .attr('width', width + margin.right + margin.left)
   .attr('height', height + margin.top + margin.bottom)
   .attr('class', 'chart')

var main = chart.append('g')
   .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
   .attr('width', width)
   .attr('height', height)
   .attr('class', 'main')   

// draw the x axis
var xAxis = d3.svg.axis()
    .scale(xscale)
    .orient('bottom')
    .ticks(6)
    .tickFormat(function (d, i) {
        return ['','everyday','once a week','several times a week','1-3 times a month','less than once a month'][d];
    });


main.append('g')
  .attr('transform', 'translate(0,' + height + ')')
  .attr('class', 'main axis date')
  .call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
  .scale(yscale)
  .orient('left')
  .ticks(25)
  .tickPadding(10)
  .tickFormat(function (d, i) {
        return ['','A','B','C','D','E','F','G','H','I'
        ,'J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X'
        ][d];
    });

main.append('g')
  .attr('transform', 'translate(0,0)')
  .attr('class', 'yAxis main axis date')
  .call(yAxis);
	
	d3.selectAll("g.yAxis g") 
        .append("line") 
            .attr("class", "gridline")
            .attr("x1", 0) 
            .attr("y1", 0)
            .attr("x2", width)
            .attr("y2", 0);

var g = main.append("svg:g"); 

g.selectAll("scatter-dots")
  .data(data)
  .enter().append("svg:circle")
      .attr("cx", function (d,i) { return xscale(d[0]); } )
      .attr("cy", function (d) { return yscale(d[1]); } )
      .attr("r", function (d) { return rscale(d[2]); } )
      .style("fill", function(d) { return color(d[2]); });
      // .attr("r", 8);
.axis path,
		.axis line {
			fill: none;
			stroke: black;
			shape-rendering: crispEdges;
		}
		
		.gridline {
			opacity: 0.25;
		}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/2.10.0/d3.v2.js"></script>


来源:https://stackoverflow.com/questions/41152438/d3-js-visualization-how-to-add-y-axis-gridlines

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!