How to wrap legend items in highcharts?

时光总嘲笑我的痴心妄想 提交于 2019-12-03 05:33:58

Edit: Actually setting the item width did work, probably a better solution.

Setting the itemWidth doesn't work for me, however you can do something like this:

labelFormatter: function() {
    var words = this.name.split(/[\s]+/);
    var numWordsPerLine = 4;
    var str = [];

    for (var word in words) {
        if (word > 0 && word % numWordsPerLine == 0)
            str.push('<br>');

        str.push(words[word]);
    }

    return str.join(' ');
}

See http://jsfiddle.net/ArmRM/13520/ for an example.

You can use:

legend: {
    itemStyle: {
        width: 90 // or whatever
    },
}

And Highcharts will wrap the items for you.

Way to wrap long legend name

legend: {
    enabled: true,
    width:555,
    itemWidth:500,
    itemStyle: {
        width:500
    }
}

as a note, in 2017 you can use textOverflow option

legend.itemStyle

CSS styles for each legend item. Only a subset of CSS is supported, notably those options related to text. The default textOverflow property makes long texts truncate. Set it to null to wrap text instead.

Setting the itemStyle on the legend has a bug. Long labels with no spaces still don't wrap.

Here is a label renderer function that wraps to a specific number of characters (I hard coded 20 into it) and will force a break in words that are longer than that:

function hcLabelRender(){
    var s = this.name;
    var r = "";
    var lastAppended = 0;
    var lastSpace = -1;
    for (var i = 0; i < s.length; i++) {
        if (s.charAt(i) == ' ') lastSpace = i;
        if (i - lastAppended > 20) {
            if (lastSpace == -1) lastSpace = i;
            r += s.substring(lastAppended, lastSpace);
            lastAppended = lastSpace;
            lastSpace = -1;
            r += "<br>";
        }
    }
    r += s.substring(lastAppended, s.length);
    return r;
}

It can be used like:

legend:{
    labelFormatter: hcLabelRender
}

If you want all items on their own lines, you can use

legend: {
    layout: "vertical"
}

You can use

labelFormatter: function() {
    return this.name; // insert your formatter function here
}

in your label and you can add html tags in the formatter. In this case you can add <br> tags to manually break lines.

Please see: http://www.highcharts.com/ref/#legend--labelFormatter

For anyone else using the useHTML option, you'll run into an issue with the default textOverflow: "ellipsis" setting messing with your wrapping.

As teran noted above, setting textOverflow: null inside itemStyle will instantly fix your wrapping when useHTML is enabled and you're trying to wrap custom HTML you've written inside legendFormatter().

Without this, the default truncation doesn't apply to your HTML (e.g. not a string) and just acts like you have overflow: hidden set.

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