Arek
Arek

Reputation: 219

How to add space between axis and line in D3 line chart?

Given this simple chart I created:

 var data  = [["2013-01-24 06:38:02.235191", 52], ["2013-01-23 06:38:02.235310", 54], ["2013-01-22 06:38:02.235330", 45], ["2013-01-21 06:38:02.235346", 53]],
  maxValue = d3.max(data, function (d) { return d[1]; }),
  margin   = {top: 20, right: 20, bottom: 50, left: 50},
  width    = 500 - margin.left - margin.right,
  height   = 300 - margin.top - margin.bottom,
  svg, x, y, xAxis, yAxis, line;

$.each(data, function(index, val) {
    val[0] = new Date(val[0]);
  });

x = d3.time.scale()
  .range([0, width])

y = d3.scale.linear()
  .domain([0, maxValue])
  .range([height, 0]);

xAxis = d3.svg.axis()
  .scale(x)
  .tickSize(4, 2, 0)
  .ticks(d3.time.days, 1)
  .tickFormat(d3.time.format("%m/%d"))
  .orient("bottom");

yAxis = d3.svg.axis()
  .scale(y)
  // .ticks(5)
  // .tickValues([0, maxValue * 0.25, maxValue * 0.5, maxValue * 0.75, maxValue])
  .tickSize(4, 2, 0)
  .orient("left");

line = d3.svg.line()
  .x(function(d) { return x(d[0]); })
  .y(function(d) { return y(d[1]); });

svg = d3.select("#chart-holder").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 + ")");

x.domain(d3.extent(data, function(d) { return d[0]; }));
y.domain(d3.extent(data, function(d) { return d[1]; }));

svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .call(xAxis)
  .selectAll("text")
    .attr("transform", function(d) {
      return "rotate(-60)translate(" + -this.getBBox().height * 1.7 + "," +
        -this.getBBox().width/4 + ")";
    });

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis);

svg.append("path")
  .datum(data)
  .attr("class", "line")
  .attr("d", line);

svg
 .selectAll("circle")
 .data(data)
 .enter().append("circle")
 .attr("fill", "#0b8da0")
 .attr("r", 3.5)
 .attr("cx", function(d) { return x(d[0]); })
 .attr("cy", function(d) { return y(d[1]); });

How can I add a space between axis and line, so it won't touch the axis.

Also is there a way to force yAxis ticks to always start from 0, no matter what is the smallest value in the data set?

Working example can be found here: http://jsfiddle.net/n7Vmr/

Upvotes: 2

Views: 7985

Answers (1)

JustDanyul
JustDanyul

Reputation: 14054

You can just change the domain of the scale used to draw the y-axis, look for the line

y.domain(d3.extent(data, function(d) { return d[1]; }));

needs to be changed, if you want it one less than the smallest value in your dataset use

y.domain([d3.min(data, function (d) { return d[1]; })-1, maxValue]);

or if you want it to start from 0, regardless of the data

y.domain([0, maxValue]);

Upvotes: 6

Related Questions