orange1
orange1

Reputation: 2939

dc.js/Crossfilter -- Create ordinal bar chart with average values for dimensions?

Full JS fiddle with data example is here: https://jsfiddle.net/ojrhn96y/2/ .

I have some data with two values: Achievement and Balance. I currently have created two text elements with dc.js that keep track of the average of both values. However, I'd like to have a bar chart with an x axis ['Achievement', 'Balance'] that then has [achievement_sum, balance_sum] as its y values, with a bar for each metric.

How would I go about creating this type of a bar chart?

I have my average values, which are created using something like:

  achievementAvg = achievement.groupAll().reduceSum(
    function(d) {
      return d.achievement;
    }),

but am not sure how to assign each of these values to separate bars.

Upvotes: 1

Views: 555

Answers (1)

Gordon
Gordon

Reputation: 20120

Since you're basically rotating the data, the behavior is not directly supported by crossfilter, which wants to filter and aggregate rows, not columns.

But you can use a "fake group" for this, as long as you don't care about being able to filter by these categories. (What would it mean? I don't want to think about it.)

First we need to create a completely useless dimension object, because dc.js wants one. If you figure out a way to filter on these categories, this is where you would implement it:

var bogus_dimension = {};

Then here's the fake group, an object which implements an all method returning an array of {key,value} pairs just like a real group:

var fake_group = {
    all: function() {
        return [{key: 'Achievement', value: achievementAvg.value()/ndx.size()},
                {key: 'Balance', value: balanceAvg.value()/ndx.size()}];
    }
}

We initialize the bar chart with an ordinal scale:

dc.barChart('#bar-chart')
    .width(200)
    .height(200)
    .dimension(bogus_dimension)
    .group(fake_group)
    .xUnits(dc.units.ordinal)
    .x(d3.scale.ordinal())

Here's a fork of your fiddle with all the code in place: https://jsfiddle.net/gordonwoodhull/x03f37bk/8/

Upvotes: 1

Related Questions