MattDionis
MattDionis

Reputation: 3616

D3 x-axis for each day of the week

I have a JSON array like the following:

[
  {
    "day": "Monday",
    "sales": 242
  },
  {
    "day": "Tuesday",
    "sales": 256
  },
  ...
]

This data covers one week, so there is an object for each day Monday through Sunday.

I have built a bar graph with D3 with a bar for each day of the week. I am now attempting to add an x-axis with a tick label for each day.

enter image description here

I've done the following to set up my y-axis:

var yScale = d3.scaleLinear()
  .domain([0, d3.max(data, function(d) {
    return d.sales;
  })])
  .range([height, 0]);

var yAxis = d3.axisLeft(yScale)
  .ticks(5);

svg.append("g")
  .call(yAxis);

This works great, but for some reason, I am stumped on how to setup my x-axis with each day of the week under the corresponding bar. Note: I am using D3 version 4.

Upvotes: 3

Views: 2372

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102174

Once your days are just strings, you can use scaleBand instead of scaleTime:

var xScale = d3.scaleBand()
    .domain(data.map(function(d){ return d.day}))
    .range([0, width])//you can use rangeRound instead
    .paddingInner(someValue);//the value of the inner padding, if any.

Then, set the x axis accordingly:

var xAxis = d3.axisBottom(xScale);

Check this snippet:

var width = 550, height = 200;

var data = [{day:"Monday"},
    {day:"Tuesday"},
    {day:"Wednesday"},
    {day:"Thursday"},
    {day:"Friday"},
    {day:"Saturday"},
    {day:"Sunday"}
];

var svg = d3.select("body")
	.append("svg")
	.attr("width", width)
	.attr("height", height);
	
var xScale = d3.scaleBand()
    .domain(data.map(function(d){ return d.day}))
    .range([0, width*0.95])
	
var xAxis = d3.axisBottom(xScale)
    .ticks(7);

svg.append("g")
	.attr("transform", "translate(0,100)")
	.call(xAxis);
text { font-size: 12px;}
<script src="https://d3js.org/d3.v4.min.js"></script>

Upvotes: 3

Related Questions