FateJudgement FateJudgement - 3 months ago 7x
HTML Question

Changing the xAxis to say Months instead of Numbers

I am currently making a line graph which shows data over 6 months. I have made the graph fine but my issue now is making the axis on the bottom say the months and each plot to be aligned with said month.

For reference I have placed a data array with the months in order and an array of the data which is used for the line. Each month corresponds to the respective data (e.g. 1st data in array = 1st month in array).

<!DOCTYPE html>
<meta charset="utf-8">
<script src="http://d3js.org/d3.v3.min.js" charset="utf-8"></script>

<style type="text/css">
h1 {
font-size: 35px;
color: darkblue;
font-family: Helvetica;
border-bottom-width: 3px;
border-bottom-style: dashed;
border-bottom-color: black;

path {
stroke: steelblue;
stroke-width: 1;
fill: none;

font-family: sans-serif;

.axis {
shape-rendering: crispEdges;

.x.axis line {
stroke: lightgrey;

.x.axis .minor {
stroke-opacity: .5;

.x.axis path {
display: none;

.y.axis line, .y.axis path {
fill: none;
stroke: #000;


<h1>Resources used per Month</h1>

<script type="text/javascript">
var m = [80, 80, 80, 80]; // margins
var w = 1000 - m[1] - m[3]; // width
var h = 400 - m[0] - m[2]; // height

var dataArrayMonths = ['April', 'May', 'June', 'July', 'August', 'September']
var data = [1.5, 1.5, 1.5, 3.6, 3.6, 2.7,];

var x = d3.scale.linear().domain([0, data.length]).range([0, w]);

var y = d3.scale.linear().domain([0, 4]).range([h, 0]);

var line = d3.svg.line()
.x(function(d,i) {
return x(i);
.y(function(d) {
return y(d);

var svg = d3.select("body").append("svg")
.attr("width", w + m[1] + m[3])
.attr("height", h + m[0] + m[2])
.attr("transform", "translate(" + m[3] + "," + m[0] + ")");

var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(true);

.attr("class", "x axis")
.attr("transform", "translate(0," + h + ")")

var yAxisLeft = d3.svg.axis().scale(y).ticks(4).orient("left");

.attr("class", "y axis")
.attr("transform", "translate(-25,0)")

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


What I am asking is how do I get the xAxis to say the 6 months I require and how do I get it to line up with the respective points on the line.

Thank you in advance!


Just add tickformat with your labels:

  var xAxis = d3.svg.axis().scale(x).tickSize(-h).tickSubdivide(true);


  var xAxis = d3.svg.axis()
                .tickFormat(function(d, i){
                    return dataArrayMonths[i/2]   // for every month return the name

Here the working jsFidlle