猿问

如何在 Highcarts 中使用数组?

我的代码中有两个数组,我想使用 Highcharts 在饼图上绘制一些数据。一个数组包含该数据的标签,另一个数组包含数据。这是我尝试过的:


arr1 = [10, 39, 30]

arr2 = ['one', 'two', 'three']



Highcharts.chart('container-2', {

  chart: {

    margin: [0, 0, 0, 0],

    spacingTop: 0,

    spacingBottom: 0,

    spacingLeft: 0,

    spacingRight: 0,

    plotBackgroundColor: null,

    plotBorderWidth: null,

    plotShadow: false,

    type: 'pie'

  },

  title: {

    text: 'Example'

  },

  tooltip: {

    pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'

  },

  plotOptions: {

    pie: {

      size: '50%',

      allowPointSelect: true,

      cursor: 'pointer',

      dataLabels: {

        enabled: true,

        format: '<b>{point.name}</b>: {point.percentage:.1f} %'

      }

    }

  },

  series: [{

    name: 'Balances',

    colorByPoint: true,

    data: {

        y: arr1,

        name: arr2,

    }

  }]

});

不幸的是,这会生成一个没有任何数据的图表。有人可以帮我找出我做错了什么吗?


HUX布斯
浏览 125回答 2
2回答

largeQ

arrays使用y和name作为属性格式化来自对象数组中的标签和数据的数据。const arr1 = [10, 39, 30];const arr2 = ["one", "two", "three"];const pieData = arr1.map((cur, index) => {&nbsp; return { name: arr2[index], y: cur };});console.info("PIEDATA::", pieData);然后将此格式化数据传递给系列数据://notice data should be an array of objects for those pie plotting values&nbsp; &nbsp; series: [{&nbsp; &nbsp; &nbsp; &nbsp; name: 'Balances',&nbsp; &nbsp; &nbsp; &nbsp; colorByPoint: true,&nbsp; &nbsp; &nbsp; &nbsp; data:pieData&nbsp; &nbsp; &nbsp; }]

叮当猫咪

y并且name应该是单一值。您必须直接将两个数组转换为一个对象:let data = {}for(let i=0;i<arr1.length;i++){&nbsp; &nbsp; data[arr2[i]] = data[arr1[i]];}然后在图表选项中:Highcharts.chart('container-2', {&nbsp; &nbsp; ...&nbsp; &nbsp; series: [{&nbsp; &nbsp; &nbsp; &nbsp; name: 'Balances',&nbsp; &nbsp; &nbsp; &nbsp; colorByPoint: true,&nbsp; &nbsp; &nbsp; &nbsp; data: data&nbsp; &nbsp; }]});
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答