如何在堆积的柱状图Highcharts中显示所有系列数据的图例?

时间:2019-05-12 09:17:56

标签: javascript highcharts

在此图表中,我想显示所有具有带状颜色的人的名字作为传说中的不同水果的传奇人物。这里有些人可以有很多种类的水果,但是我不想重复显示名字。这里只显示系列名称,但是我想在底部显示所有人的名字。有人可以帮我吗?

Highcharts.chart('container', {
    chart: {
        type: 'column'
    },
    title: {
        text: ''
    },
    xAxis: {
        categories: ['Apples', 'Oranges','Bananas']
    },
    yAxis: {
        min: 0,
        title: {
            text: ''
        },
        stackLabels: {
            enabled: true,
            style: {
                fontWeight: 'bold',
                color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
            }
        }
    },
    tooltip: {
        headerFormat: '<b>{point.x}</b><br/>',
        pointFormat: '{point.name}: {point.y}<br/>Total: {point.stackTotal}'
    },
    plotOptions: {
        column: {
            stacking: 'normal',
            dataLabels: {
                enabled: true,
                color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white'
            }
        }
    },
    credits: {
        enabled: false
    },
    series : [{
    	data : [{
				x:0,
				y:3,		
				name:'John',
				color:'#FF5733'
			},
			{
				x:0,
				y:5,
				name:'Parker',
				color:'#009900'
			},{
				x:0,
				y:1,
				name:'Adam',
				color:'#95FF33'
			},{
				x:1,
				y:5,
				name:'Alex',
				color:'#E3FF33'
			},{
				x:1,
				y:3,
				name:'Pukal',
				color:'#33BDFF'
			},{
				x:1,
				y:4,
				name:'Mark',
				color:'#FB33FF'
			},{
				x:2,
				y:3,
				name:'John',
				color:'#FF5733'
			},{
				x:2,
				y:4,
				name:'Parker',
				color:'#009900'
			},{
				x:2,
				y:2,
				name:'Mark',
				color:'#FB33FF'
			}]
		}]
});
<script src="https://code.highcharts.com/highcharts.js"></script>
	<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

2 个答案:

答案 0 :(得分:2)

我将数据转换为多个序列而不是一个序列,如下所示:

{
  series : [
    { name: "John", color: "#FF5733", data: [3, 0, 3] }
    { name: "Parker", color: "#009900", data: [5, 0 4] }
    .. etc ...
  ]
}

然后,Highcharts将自动使用该人的姓名作为图例。

这里是Fiddle,以显示我的意思。

我使用以下代码将数据转换为多个序列:

var data = [];
var seriesLookup = {};
original.forEach(function(item){
  var series = seriesLookup[item.name];
  if(!series){
    series = {
      name: item.name,
      color: item.color,
      data: [0, 0, 0]
    };
    data.push(series);
    seriesLookup[item.name] = series;
  }
  series.data[item.x] = item.y;
});

然后我将tooltip.pointFormat改为使用series.name而不是point.name

tooltip: {
  headerFormat: '<b>{point.x}</b><br/>',
  pointFormat: '{series.name}: {point.y}<br/>Total: {point.stackTotal}'
},

我还使用dataLabels.formatter忽略了0个值。

dataLabels: {
  enabled: true,
  color: (Highcharts.theme && Highcharts.theme.dataLabelsColor) || 'white',
  formatter: function(){
    return (this.y!=0) ? this.y : "";
  }
}

答案 1 :(得分:0)

您也可以只设置legendType: 'point'

series: [{
    legendType: 'point',
    data: [ ... ]
}]

实时演示: http://jsfiddle.net/BlackLabel/9kqLsfza/