Can you add a legend to a dc.js Bubble Chart?

爷,独闯天下 提交于 2019-12-11 06:02:24

问题


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
     };
   });
 };
  1. Give the specific values which you want to show in the legend
  2. The legend needs a reference back to the chart
  3. Specify the label for each value - I'm just using the value itself
  4. 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 at d.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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!