Could anyone tell me how to customize the brush to display filter values as labels?
I would like to get the same style as the one marked with arrows in the following screenshot but I don't know how to get it, and I haven't seen any example.
This is a great question, and I am surprised no one has asked this before. Obviously, dc.js can display the filter values in the text above the chart, but putting it right on the brush is really cool!
Any dc.js chart will allow you to listen for the pretransition
event and draw your own annotations using D3.
Let's do that:
chart.on('pretransition', function(chart) {
let brushBegin = [], brushEnd = []; // 1
if(chart.filter()) {
brushBegin = [chart.filter()[0]]; // 2
brushEnd = [chart.filter()[1]];
}
let beginLabel = chart.select('g.brush') // 3
.selectAll('text.brush-begin')
.data(brushBegin); // 4
beginLabel.exit().remove(); // 5
beginLabel = beginLabel.enter()
.append('text') // 6
.attr('class', 'brush-begin') // 7
.attr('text-anchor', 'end')
.attr('dominant-baseline', 'text-top')
.attr('fill', 'black')
.attr('y', chart.margins().top)
.attr('dy', 4)
.merge(beginLabel); // 8
beginLabel
.attr('x', d => chart.x()(d))
.text(d => d.toFixed(2)); // 9
let endLabel = chart.select('g.brush')
.selectAll('text.brush-end')
.data(brushEnd);
endLabel.exit().remove();
endLabel = endLabel.enter()
.append('text')
.attr('class', 'brush-end')
.attr('text-anchor', 'begin')
.attr('dominant-baseline', 'text-top')
.attr('fill', 'black')
.attr('y', chart.margins().top)
.attr('dy', 4)
.merge(endLabel);
endLabel
.attr('x', d => chart.x()(d))
.text(d => d.toFixed(2));
})
This looks like a lot of code; it's really doing the same thing twice, once for each label. Let's look at how the first label is shown.
d.brush
), then select the elements we want to create, update, or destroy, thenbrush-begin
which we just used in binding. Most of these attributes are to get the label position correct.https://jsfiddle.net/gordonwoodhull/w4xhv8na/33/
Getting white-on-black labels is actually not trivial but I hope to return to that later.