user1888521
user1888521

Reputation: 135

Display x axis properly on stacked bar chart

Hey so I'm having difficulty with the positioning of my stacked bar chart. It's showing up, I'm just having difficulty declaring it's x axis. Here is the jsfiddle: http://jsfiddle.net/E2HST/

var xTimeScale = d3.time.scale().
domain([new Date(data[0].date), d3.time.day.offset(new Date(data[data.length - 1].date), 1)])
.range([0, width]);

is obviously part of the problem, I pulled code and have unfortunately fallen into the trap of not fully understanding it.

var bars = svg.selectAll(".bar")
  .data(data).enter()
  .append("g")
  .attr("class","bar")
  .attr("transform", function(d){
        return "translate("+xTimeScale(d.date)+",0)"
})

I've tried swapping in d.year for d.date seeing as there is no more d.date but it's throwing up errors. Any help would be greatly appreciated.

Upvotes: 1

Views: 427

Answers (1)

Josh
Josh

Reputation: 5470

The simple answer is that the objects in your data array do not have a date key, so your xTimeScale domain is undefined. An easy way to correct this would be to create this key for each data item:

data.forEach( function(d) { d.date = new Date(d.year, 0, 1); });

Which creates the date as January 1st of the year variable. This basically solves your x-axis problem.

I would, however, suggest that your data would be better suited to using an ordinal scale, since you only have yearly data.

A couple of other small things:

  • Your x-axis definition has way too many ticks, consider changing this
  • Consider adding css styles for .axis elements, to improve readability

An updated fiddle with these slight changes is at http://jsfiddle.net/E2HST/1/

Upvotes: 2

Related Questions