Search code examples
highchartstooltiplegend

How to wrap legend items in highcharts?


I have a big problem using highcharts, because I have been trying for hours to wrap legend items if they very long.

I have tried to set legend and legend item width, but my text still get out from a legend. Only thing that I found is to change highcharts.src.js but I think that's not a way to solve this problem.

Here my code:

<script type="text/javascript">
  var chart;
  $(document).ready(function() {
    chart = new Highcharts.Chart({
      chart: {
        renderTo: 'graph_container',
        defaultSeriesType: 'line',
        zoomType: 'y',
        marginRight: 130,
        marginBottom: $ {
          marginBottom
        }
      },
      title: {
        x: -10,
        text: null
      },
      xAxis: {
        title: {
          text: '<fmt:message key="html.time" bundle="${msg}"/>',
          align: 'high'
        },
        categories: [$ {
          years
        }]
      },
      yAxis: {
        title: {
          text: '<fmt:message key="html.value" bundle="${msg}"/>',
          align: 'high'
        },
        plotLines: [{
          value: 0,
          width: 1,
          color: '#808080'
        }]
      },
      tooltip: {
        style: {
          fontSize: '9pt',
          width: '400px', //,
          wrap: 'hard'
        },
        formatter: function() {
          return '<b>' + this.series.name + '<br>' +
            +this.x + ': ' + this.y + '</b>';
        }
      },
      legend: {
        layout: 'vertical',
        width: 600,
        floating: true,
        align: 'center',
        verticalAlign: 'bottom',
        borderWidth: 1,
        itemWidth: '500px'

      },
      credits: {
        enabled: false
      },
      exporting: {
        enabled: false
      },
      series: [ <
        c: forEach items = "${graphValues}"
        var = "value"
        varStatus = "counter" >
        <
        c: if test = "${counter.count != 1}" > , < /c:if> {
          name: '${value.name}',
          data: $ {
            value.jsonData
          }
        } <
        /c:forEach>
      ]
    });


  });
</script>

Solution

  • 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.