Gina Gina - 1 year ago 218
CSS Question

Line Chart d3 js-- x axis months

I'm trying to do a simple line graph that has months Jan - Dec in the x axis and number of assignments posted on my company's website for the y. I'm having a bit of trouble mapping the y domain... and basically understanding how this api is supposed to work. I find plenty of examples with parsing for date, or a numerical value x axis, but I can't seem to get it right with months.

I've been tweaking with this code for so long, I'm not even sure what I'm looking at.

Any help is greatly appreciated for a young noob.

Here is the gist:

my styling looks like:

.axis path,
.axis line {
fill: none;
stroke: #000;
shape-rendering: crispEdges;

.axis text {
font: 10px sans-serif;

.line {
fill: none;
stroke: steelblue;
stroke-width: 1.5px;

Answer Source

I'd like to show how I actually ended up implementing this graph: per AmeliaBR's recommendation and Mike Bostock's Month Axis example, I decided to make my line chart with x and y being linear scales, and a variable called xLabels, to be a formatted time scale for the xAxis. Like so,

var xLabels = d3.time.scale().domain([new Date(2013, 0, 1), new Date(2013, 11, 31)]).range([0, w]);
    var x = d3.scale.linear().domain([0, data.length]).range([0, w]);
    var y = d3.scale.linear().domain([0, d3.max(data)]).range([h, 0]);

I plotted my line like I would a normal linear scale, but for xAxis:

var xAxis = d3.svg.axis().scale(xLabels).ticks(d3.time.months).tickFormat(d3.time.format("%B")).tickSize(-h).tickSubdivide(true);
          .attr("class", "x axis") 
          .attr("transform", "translate(0," + h + ")")

I passed in my xLabels for the scale, and formatted my ticks to be months.

Here is the working example on a jsfidde: