Get Information from a selected bar - dc.js - dc.js

I create charts with crossfilter and dc.js.
In Chart Nr.1 you can see how many guests visit a resturant per day, and the second chart shows the age of the guests. Both are bar charts.
For some calculations I need information from the selected bar. For Example:
In Chart Nr.1 you select the date 16/03/2019 and you see in Chart Nr.2 100 Guests were older then 50 and 30 younger then 50.
Now I need a variable with the 100 Guests, and another with the 30 Guests.
How I get at the data behind the aggregated value of each bar?

You could override the bar charts onClick function to save the value selected:
var valueSelected;
dc.override(barChart, 'render', function () {
barChart.selectAll('rect').on("click", function (d) {
valueSelected = d.data.value;
//call original onClick:
barChart.onClick(d);
});
barChart.selectAll('text.barLabel').on("click", function (d) {
valueSelected = d.data.value;
//call original onClick:
barChart.onClick(d);
});
});

Related

How to registery event handlers on the individual categories of a AMCharts v4 CategoryAxis

I have seen https://www.amcharts.com/docs/v4/concepts/event-listeners/ and
https://www.amcharts.com/docs/v4/reference/categoryaxis/#Events
categoryAxis.events.on('hit', function (ev) {
console.log('clicked on ', ev.target)
}, this)
works. However, this returns the complete CategoryAxis. I would like to distinguish on which catgeory the user clicked.
e.g. categoryAxis.category.template.events.on('hit', function (ev) does not exist.
You need to add the hit event listener on the axis renderer's label template in order to capture the category label that was clicked:
categoryAxis.renderer.labels.template.events.on('hit', function(ev) {
alert(ev.target.dataItem.category)
})

Unable to reset the focus ordinal bar chart

I am trying to reset after choosing some of the individual's bar.
index.html: (line no. 62)
<span>
reset
</span>
This seems not to work. I was able to reset all the graphs pie chart, line chart, etc but not this one.
Those two ordinal graphs are created in index.js like this:
var focus = new dc.barChart('#focus');
var range = new dc.barChart('#range');
https://blockbuilder.org/ninjakx/483fd69328694c6b6125bb43b9f7f8a7
Update:
It looks weird now Coz it's showing a single bar and all the bar have got invisible but I want them to be visible (in gray colour) but not clickable.
This example replaces the built-in filtering functionality of the bar chart with its own implementation of ordinal selection, because the chart has a linear scale.
The example uses a global variable focusFilter to store the current selection. We need to empty this out and we also need to update the dimension filter as the original filterAll would do, pulling that code out of the click handler:
focus.applyFilter = function() { // non-standard method
if(focusFilter.length)
this.dimension().filterFunction(function(k) {
return focusFilter.includes(k);
});
else this.dimension().filter(null);
};
focus.filterAll = function() {
focusFilter = [];
this.applyFilter();
};
This will also allow dc.filterAll() to work, for a "reset all" link.
Fork of your block.
For some reason, I could not get the original
reset
links to work at all in this block, so I replaced them with the equivalent D3 click handlers:
d3.select('#reset-focus').on('click', () => {
focus.filterAll();
dc.redrawAll();
})
d3.select('#reset-all').on('click', () => {
dc.filterAll();
dc.redrawAll();
})
I also updated the focus ordinal bar example. Note that automatic hiding/showing of the reset link doesn't work because the chart still has an irrelevant range filter inside of it.

dc.js: expense tracker, show distribution for each month in a pie chart

I'm trying to make a Pie chart that shows each months expenses on different category.Like,when I give January ,the slices should display Grocery,fuel,rent etc.How can I make it with this data?
code
function show_monthly_exp_distribution(ndx) {
var dim = ndx.dimension(dc.pluck('Month'));
var group = dim.group().reduceCount(dc.pluck());
dc.pieChart("#exp-pie")
.height(300)
.width(800)
.radius(70)
.transitionDuration(1000)
.dimension(dim)
.group(group)
.legend(dc.legend().gap(7));
}
csv data
Month,Utility Bills,Groceries,Dining Out,Fuel,Rent,totalexp
January,100,500,100,90,1000,1400
February,120,450,50,120,1000,1740
March,130,550,120,60,1000,1860
April,100,300,80,150,1000,1630
May,90,600,75,80,1000,1845
June,130,560,150,90,1100,2030
July,70,610,120,100,1100,2000
August,120,459,100,80,1100,1859
September,140,432,80,90,1100,1842
October,60,456,110,110,1100,1836
November,80,487,60,180,1200,2007
December,150,390,210,100,1200,2050
As Gordon suggested, start by changing the format of your data so you have only one datapoint per row. If you can't change the data on the csv, you can do it in js (code not tested, might work directly... or not ;)
var data = [];
var type = "Utility Bills,Groceries,Dining Out,Fuel,Rent".split(",");
d3.csv("yourcsv", function(d) {
type.forEach(function(c){
data.push({month:d.month,type:c,amount:+d[c]});
});
return null; //doesn't matter what you return, discard the initial csv anyway)
}).then (function(dummy){
ndx=crossfilter(data);
});
Once you have done that, you can easily have one graph to filter the month (or selectMenu graph) and your pieChart

dc.js - dynamically change valueAccessor of a stacked layer in a lineChart and redraw it

I am trying to realize a dashboard to display basic data.
I am actually completely stuck on an issue. Strangely enough, I couldn't find anything even similar to it online, so I don't have many leads on how to move forward.
I have mainly two charts:
a lineChart called "stackChart" that
displays consumption as a base layer with its valueAccessor function
dispalys production as a stacked layer with its value Accessor function
a barChart called "volumeChart" that is simply the rangeChart for the lineChart
I use radio buttons to select whether to aggregate the grouped data by sum or by average (using the same approach as this example) and then I just use:
stackChart.valueAccessor(/*function with new value (avg or sum)*/);
dc.redrawAll();
to refresh the base layer (consumption).
What I don't manage to do is to refresh the "stacked layer" by updating its valueAccessor! I can't find any way to access its valueAccessor (or, worst case, just completely remove the stacked layer and then add a new refreshed stacked layer using just ".stack(...)").
Here is the respective part of my code where the chart is built:
// Charts customization #js
stackChart
.renderArea(true)
.height(350)
.transitionDuration(1500)
.dimension(dateDim)
.group(powByTime, "Consumption")
// BASE LAYER valueAccessor HERE
.valueAccessor(function(d) { return d.value.conSum; })
.x(d3.time.scale().domain([minDate, maxDate]))
.xUnits(d3.time.days)
.elasticY(true)
.renderHorizontalGridLines(true)
.legend(dc.legend().x(80).y(0).itemHeight(13).gap(5))
.brushOn(false)
// STACKED LAYER HERE
.stack(powByTime, "Production", function(d) { return d.value.prodSum; })
.rangeChart(volumeChart)
.controlsUseVisibility(true)
;
And here is where I look for changes in the radio buttons and re-draw the layers:
// Listen for changes
d3.selectAll('#select-operation input')
.on('click', function() {
var aggrMode = this.value; // fetch "avg" or "sum" from buttons
// UPDATE BASE LAYER HERE:
stackChart.valueAccessor(function(d) { var sel = accessors[aggrMode]['consPow']; return d.value[sel]; });
// ???HOW TO UPDATE STACKED LAYER valueAccessor function???
//stackChart.stack.valueAccessor(function(d) { var sel = accessors[aggrMode]['prodPow']; return d.value[sel]; });
dc.redrawAll();
});
If you need more details on what I am trying to do and full code you can check here.
As a reference, here is what it looks like:
I don't really know dc.js, but it may be possible that you can't change an accessor once it's been set. Try writing a single function for your accessor that will return either the sum or the average, depending on the state of some variable that you can set.
#Ryan's solution will probably work fine (and may be a better design), but here's the lowdown on the dc.js API with respect to stacking, in case you need it.
As described in this issue the group and stack API is pretty weird. It grew organically, in a backward-compatible way, so both the stacks and the value accessors on top of the stacks sort of branch out in a beautiful fractal of... well, no it's pretty messy.
But the issue also suggests the solution for your problem. Since chart.group() resets the set of stacks, just go ahead and build them all from scratch in your event handler:
stackChart.group(powByTime, "Consumption") // this resets the stacks
.valueAccessor(function(d) { var sel = accessors[aggrMode]['consPow']; return d.value[sel]; })
.stack(powByTime, "Production", function(d) { var sel = accessors[aggrMode]['prodPow']; return d.value[sel]; });
Internally it's just emptying an array of layers/stacks and then populating it with some references.
This is quite efficient since dc.js doesn't store your data except where it is bound to the DOM elements. So it is the same amount of work to redraw using the old group and value accessor as it is to redraw using new ones.

How to inject data in tooltip

I'm using angularjs-nvd3-directives to render my charts. I have an issue on a chart where I have 2 series, one of the serie has tooltip disabled using chart.lines.interactive(false) and the other serie has it enabled.
I want to display in the remaining tooltip the value of the other serie as well as the current serie. A little bit like this: http://nvd3.org/examples/cumulativeLine.html
With angularjs-nvd3-directives you have to specify the tooltipContent function that will render the tooltip. This function takes 5 parameters:
$scope.toolTipContentFunction = function() {
return function(key, x, y, e, graph) {
...
}
}
graph is the chart function that is returned by nvd3. I tried to get the data from it but I cannot find any methods to get it.
How could I do it ?
Maxime

Resources