johny
johny

Reputation: 159

How to change xaxis label in D3 chart?

The following code shows you my current chart. How I can edit the label of the xaxis to show the years "2015", "2016", "2017", "2018" and "2019"? I am really new in this D3.

var data = new Array (1, 2, 3, 4, 5);
var x_scale = d3.scale.linear()
      .domain([0,d3.max(data, function(d,i) { return i+1 })])
      .range([62,540])
    var xAxis = d3.svg.axis()
      .scale(x_scale)
      .tickSize(0,0)
      .ticks(5)
      .tickPadding(6)
      .orient("bottom");
    d3.select("svg").append("g")
      .call(xAxis)
      .attr("class","xaxis")
      .attr("transform","translate(0,364)");


var y_scale = d3.scale.linear()
  .domain([d3.max(data, function(d) { return d }),0])
  .range([54,364])
var yAxis = d3.svg.axis()
  .scale(y_scale)
  .tickSize(-10,0)
  .ticks(5)
  .tickPadding(6)
  .orient("left");
d3.select("svg").append("g")
  .call(yAxis)
  .attr("class","yaxis")
  .attr("transform","translate(62,0)");


var saeule = d3.select("#saeulen").append("g")
  .attr("class","saeule")
  .style("color","#F49600");
var bar_padding=10;
var bar_width=x_scale(1)-x_scale(0)-bar_padding;
saeule.selectAll("g")
  .data(data)
  .enter() 
  .append ("rect")
    .attr("fill","#F49600")
    .attr("x" , function (d,i) { return (x_scale(i+1) - (bar_width/2)) })
    .attr("y", function (d,i) { return (y_scale(d)) })   
    .attr("width", bar_width)
    .attr("height", function (d,i) { return (y_scale(0)-y_scale(d)) });

Upvotes: 2

Views: 2879

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

You can give your own tick format like this on x axis:

var xAxis = d3.svg.axis()
  .scale(x_scale)
  .tickSize(0,0)
  .ticks(5)
  .tickPadding(6)
  .orient("bottom")
  .tickFormat(function(d){return d+2015;});//will return 2015 for 0 2016 for 1 etc.

working code here

Upvotes: 5

Related Questions