dongzhang1875 2018-01-25 07:13
浏览 337
已采纳

chartjs的多个气泡图数据集

I have an array called main_arr which has multiple data arrays within it.

So i am using a bubble chart to show all these different arrays in different colors to distinguish them

var myBubbleChart = new Chart(ctx, {
    type : 'bubble',
    data : {
        datasets : [
            {
                label : 'Group 1: ' + main_arr[0].length,
                data : main_arr[0],
                backgroundColor : 'lightblue'
            }, {
                label : 'Group 2: ' + main_arr[1].length,
                data : main_arr[1],
                backgroundColor : 'pink'
            }
        ],
    },
    options : {
        scales : {
            yAxes : [{
                    ticks : {
                        beginAtZero : true,
                        min : 0,
                        max : 100
                    }
                }
            ],
            xAxes : [{
                    ticks : {
                        beginAtZero : true,
                        min : 0,
                        max : 10
                    }
                }
            ],
        }
    }
});

This works perfectly. But i want to make it dynamic so that i dont need to hard code main_arr[0], main_arr[1]...so on for each array.

So i want to use a for loop that loops through the main_arr and initialize the dataset.

datasets : [
    for (var i = 0; i < main_arr.length; i++) { {
            label : 'Group ' + i + ': ' + main_arr[i].length,
            data : main_arr[i],
            backgroundColor : 'lightblue'
        }
    }
],

This gives an error in the console:

Uncaught SyntaxError: Unexpected token for

So how to achieve this ?

  • 写回答

1条回答 默认 最新

  • dongshi6844 2018-01-25 07:58
    关注

    You can use an immediately invoked function like below:

    datasets:
          (function (main_arr) {
              var out = [];
              for(var i=0; i<main_arr.length; i++) {
                out.push({
                    label: 'Group ' + i + ': ' + main_arr[i].length,
                    data: main_arr[i],
                    backgroundColor: 'lightblue'
                  });
              }
              return out;
          })(main_arr)
    },
    

    The function creates the datasets array and returns it to datasets property of chart options object.

    Here is a fiddle: https://jsfiddle.net/beaver71/4nf41tq9/

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MYSQL 多表拼接link
  • ¥15 关于某款2.13寸墨水屏的问题
  • ¥15 obsidian的中文层级自动编号
  • ¥15 同一个网口一个电脑连接有网,另一个电脑连接没网
  • ¥15 神经网络模型一直不能上GPU
  • ¥15 pyqt怎么把滑块和输入框相互绑定,求解决!
  • ¥20 wpf datagrid单元闪烁效果失灵
  • ¥15 券商软件上市公司信息获取问题
  • ¥100 ensp启动设备蓝屏,代码clock_watchdog_timeout
  • ¥15 Android studio AVD启动不了