Skip to content Skip to sidebar Skip to footer

How To Fix Chart Legends Width-height With Overflow Scroll In Chartjs

I want to create pie chart for my project, so I am using ChartJS for it, but there are some issues with chartJS, If I am work with 10 to 20 data-field that time chart is looks good

Solution 1:

You can try one thing

Try to separate the legend into an different div. now you have full control of the div you can use custom placement and css of your own consider the following code :

 <div id="js-legend" class="chart-legend"></div>
 document.getElementById('js-legend').innerHTML = myChart.generateLegend();

For reference see this FIDDLE

For handling legend interactive you need to extend the callback function and manipulate like this :

$("#js-legend > ul > li").on("click",function(e){
        var index = $(this).index();
        $(this).toggleClass("strike")
        var ci = e.view.myChart;
        var curr = ci.data.datasets[0]._meta[0].data[index];
        curr.hidden = !curr.hidden
        ci.update();
}) 

For Legend in action see this FIDDLE

Explanation :

I binded chart to window so that event view can get it, and later by the index manipulated the data and updated runtime used few css tricks to illustrate the strike effect.

Solution 2:

I did not found any solution for this, but you can turn off legend if too many labels are to be shown (I did it in my project) - here is set to max 15 labels:

options : {
        responsive:true,
        maintainAspectRatio:false,
        layout: {
          padding: {
             left     :0,
             right    :0,
             top      :0,
             bottom   :0
          }
        },
        animation: {
          duration :5000
        },
        legend: {
          display:this.chartValues.length<=15,
        }
}

You can also make place for rendering charts bigger. Add this to your scss file:

.chartjs-render-monitor{
    height: 300px!important;
}

I hope it gonna help someone

Solution 3:

As mentioned in other answers, a possible solution is externalize the legend as plain HTML div, on which you have full control.

Now, in ChartJS v3 the chart.generateLegend() function has been removed.

The maintainers, though, have published the so called htmlLegend plugin which externalises the legend, here is the link:

HTML Legend (External DIV) - ChartJS Docs

The plugin creates an interactive legend whose items can be clicked to show/hide datasets as in the original one.

NOTE: although having a scrollable legend might come in handy, having so many items in a legend could make the chart illegible and should make one consider representing data in a different way, perhaps by splitting data in more charts or introducing search functions

Post a Comment for "How To Fix Chart Legends Width-height With Overflow Scroll In Chartjs"