Search code examples
d3plus

Setting the order in d3plus stacked area plot


How can I set the ordering of areas in a stacked area plot in d3plus?

I use the following example from http://d3plus.org/examples/basic/9029462/:

<script>
  // sample data array
  var sample_data = [
    {"year": 1993, "name":"alpha", "value": 20},
    {"year": 1994, "name":"alpha", "value": 30},
    {"year": 1995, "name":"alpha", "value": 60},
    {"year": 1993, "name":"beta", "value": 40},
    {"year": 1994, "name":"beta", "value": 60},
    {"year": 1995, "name":"beta", "value": 10},
    {"year": 1994, "name":"gamma", "value": 10},
    {"year": 1995, "name":"gamma", "value": 40}
  ]
  // instantiate d3plus
  var visualization = d3plus.viz()
    .container("#viz")  // container DIV to hold the visualization
    .data(sample_data)  // data to use with the visualization
    .type("stacked")    // visualization type
    .id("name")         // key for which our data is unique on
    .text("name")       // key to use for display text
    .y("value")         // key to use for y-axis
    .x("year")          // key to use for x-axis
    .time("year")       // key to use for time
    .draw()             // finally, draw the visualization!
</script>

The ordering is Gamma, Beta, Alpha. How can I make a custom ordering?

I tried .order({'value': ['Beta', 'Alpha', 'Gamma']} without effect. .order({'sort': 'asc'}) however works. Then again, .order({'agg': 'min'}) (which should yield Gamma, Alpha, Beta) doesn't work either.


Solution

  • I just had a similar issue with a stacked bar chart. I think it's a bug in d3plus. Change your x-axis field (in your case 'year') to a string field instead of an integer. Then ordering might start working.

    e.g. {"year": "1993", "name":"alpha", "value": 20}