问题
Is it possible to make a legend for Bubble Chart?
Somebody asked this question a few years ago, but I cannot find a good answer for it. Does anybody have an example of where they made a legend for a bubble chart using dc.js?
回答1:
You can manually add legend support to any chart which does not have it already by defining the .legendables()
function. Although many charts (e.g. pie, line, bar, scatter, sunburst) support it, the default is to return an empty array.
One reason why it might not be defined is that a chart doesn't necessarily know which values to show. But presumably you do, so you can specify them manually.
As an example, I've put the bubble chart from the dc.js stock example in a fiddle, and patched in legendables
like this:
yearlyBubbleChart.legendables = function() {
return [500, 250, 0, -250, -500].map(function(v) { // 1
return {
chart: yearlyBubbleChart, // 2
name: v, // 3
color: yearlyBubbleChart.getColor({value: {absGain: v}}) // 4
};
});
};
- Give the specific values which you want to show in the legend
- The legend needs a reference back to the chart
- Specify the label for each value - I'm just using the value itself
- Give a color. This is the most complicated part. You could just specify a color directly, but I think it's better to use the color function (scale) that the chart uses. This means you have to produce artificial data that looks like your group values. Here the
colorAccessor
expects to look atd.value.absGain
so we build data that looks like that.
After this, adding the legend to the chart is completely normal:
yearlyBubbleChart.legend(dc.legend().x(600).y(20));
Demo fiddle
来源:https://stackoverflow.com/questions/50497178/can-you-add-a-legend-to-a-dc-js-bubble-chart