Reputation: 133
I would like to separate legends with lines, for example I want to have 2 legends per line.
I tried to use labelFormatter but the < br/ > tag brakes the line only in the label's text not the line for legends.
Highcharts.chart('container', {
...
legend: {
enabled: true,
useHTML: true,
labelFormatter: function() {
if (this.index == 2) {
return this.name + '<br/>';
} else {
return this.name;
}
}
},
...
});
Demo: https://jsfiddle.net/ivane_gkomarteli/t7ep0weq/
How can I change the labelFormatter so I have 2 legends per line?
UPDATE
Setting itemWidth and width doesn't solve my problem because I want to break the line according to an 'if else condition'. For example:
...
labelFormatter: function() {
if (something == true){
if (this.index == 2) {
return this.name + '<br/>';
} else {
return this.name;
}
} else {
if (this.index == 4) {
return this.name + '<br/>';
} else {
return this.name;
}
}
}
...
Possible output:
Upvotes: 0
Views: 1642
Reputation: 5826
Highcharts doesn't support that kind of layout manipulation on legend by default.
The solution here could be extending the Highcharts core so that it supports 2 legends or more.
Example for 2 legends:
(function(H) {
var merge = H.merge;
H.wrap(H.Legend.prototype, 'getAllItems', function() {
var allItems = [],
chart = this.chart,
options = this.options,
legendID = options.legendID;
H.each(chart.series, function(series) {
if (series) {
var seriesOptions = series.options;
// use points or series for the legend item depending on legendType
if (!isNaN(legendID) && (seriesOptions.legendID === legendID)) {
allItems = allItems.concat(
series.legendItems ||
(seriesOptions.legendType === 'point' ?
series.data :
series)
);
}
}
});
return allItems;
});
H.wrap(H.Chart.prototype, 'render', function(p) {
var chart = this,
chartOptions = chart.options;
chart.topLegend = new H.Legend(chart, merge(chartOptions.legend, chartOptions.topLegend, {
legendID: 0
}));
chart.bottomLegend = new H.Legend(chart, merge(chartOptions.legend, chartOptions.bottomLegend, {
legendID: 1
}));
p.call(this);
});
H.wrap(H.Chart.prototype, 'redraw', function(p, r, a) {
var chart = this;
p.call(chart, r, a);
chart.leftLegend.render();
chart.rightLegend.render();
});
H.wrap(H.Legend.prototype, 'positionItem', function(p, item) {
p.call(this, item);
});
})(Highcharts);
Live demo: http://jsfiddle.net/BlackLabel/6ob2qs1c/
Legends can be positioned via their x
& y
properties. chart.marginBottom
creates some space for the legends.
Upvotes: 0
Reputation: 12717
I've achieved layouts like this by setting the legend itemWidth and width:
legend: {
enabled: true,
itemWidth: 200,
width:400,
align: 'center'
},
https://jsfiddle.net/t7ep0weq/1/
Upvotes: 1