Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set fixed no. of ticks on axis in d3.js?

Tags:

d3.js

I am trying to display data in bar graph, in which there is need to show the max value possible in a category. However when using tick() method of d3.js it automatically adjust the ticks to the max value in the data set.

Desired x-axis ticks :

c1 -----------> 5

c2 ------> 3


1 2 3 4 5 6 7 8 9 10

like image 490
exgenome Avatar asked Sep 21 '16 21:09

exgenome


1 Answers

Axis ticks can be specified using ticks

var data = [{"closePriceDate":"Apr-8-2016","closePrice":93.24},{"closePriceDate":"Apr-9-2016","closePrice":95.35}];

var margin = {top: 20, right: 20, bottom: 30, left: 50},
    width = 500 - margin.left - margin.right,
    height = 100 - margin.top - margin.bottom;

var formatDate = d3.time.format("%b-%e-%Y");

var x = d3.time.scale()
    .domain(d3.extent(data, function(d) { return formatDate.parse(d.closePriceDate); }))
    .range([0, width]);

var xAxis = d3.svg.axis()
    .scale(x)
	.ticks(4) //specify number of ticks 
    .orient("bottom");

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 + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis);
.axis path,
.axis line {
  fill: none;
  stroke: #000;
  shape-rendering: crispEdges;
}
<script src="https://d3js.org/d3.v3.min.js"></script>
like image 77
Aravind Cheekkallur Avatar answered Sep 22 '22 21:09

Aravind Cheekkallur