Reputation: 5231
Somewhat related to this question.
I would like to add a legend to a scatterplot using dc.js, ideally with the possibility of highlighting points based on hover/click of the corresponding legend. The source code seems to indicate that color
is "legendable" for scatterplots, but I cannot find any examples where this is done.
Running the code below in the browser triggers an error:
tmp.html:26 Uncaught TypeError: Cannot read property 'key' of undefined at Object.myChart.dimension.group.colorAccessor.d (tmp.html:26) at Object._chart.getColor (color-mixin.js:149) at Object._chart.legendables (scatter-plot.js:360) at Object._legend.render (legend.js:45) at Object._chart.render (base-mixin.js:703) at Object.dc.renderAll (core.js:230) at tmp.html:33
<!DOCTYPE html><html><head><title></title>
<link rel="stylesheet" type="text/css" href="dc.css"/>
<script type="text/javascript" src="https://d3js.org/d3.v5.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/crossfilter2/1.4.6/crossfilter.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/dc/3.0.9/dc.js"></script>
</head><body>
<div id="chart"></div>
<script type="text/javascript">
dc.config.defaultColors(d3.schemeCategory10);
var myChart = dc.scatterPlot("#chart");
let input = [{x:0,y:0,c:1}, {x:1,y:1,c:0},{x:0.5,y:0.5,c:2}];
(function(data) {
var ndx = crossfilter(input),
dims = ndx.dimension( d => [+d.x,+d.y,+d.c]),
grp = dims.group();
myChart
.dimension(dims)
.group(grp)
.colorAccessor(d=> +d.key[2])
.x(d3.scaleLinear().domain(d3.extent(d3.extent(input, d => +d.x))))
.valueAccessor(d => +d.key[1])
.brushOn(false)
.legend(dc.legend().x(750).y(10).itemHeight(13).gap(5));
})(input);
dc.renderAll();
</script></div></body></html>
Upvotes: 1
Views: 372
Reputation: 20150
Yes, unfortunately it is a bug that was reported a long time ago, but has never been fixed. The scatter plot is calling _chart.getColor()
with no arguments.
https://github.com/dc-js/dc.js/issues/1138#issuecomment-217861014
Even if it's fixed, it's only returning one legendable, so I think it will only work for the scatter-series case. If you want to display legend items for each color in your chart, you'll have to generate that data yourself:
myChart.legendables = function () {
var byColor = {};
myChart.group().all().forEach(function(d) {
var color = myChart.colors()(myChart.colorAccessor()(d));
byColor[color] = {
chart: myChart,
name: 'color ' + myChart.colorAccessor()(d),
color: color
};
})
return Object.values(byColor);
};
Maybe the chart should do something this automatically. One complication is that there currently aren't any names defined for colors - here I just pasted 'color '
with the value returned by the color accessor, but you presumably have better names in your actual data set.
Upvotes: 1