score:1

you can make line legend by changing width of legend box (for example 2px), it will be vertical line but it's looks nice too

plugins: {
   legend: {
       display: true,
       labels: {
           boxwidth: 2
       }
    }
}

score:2

just to improve on this solution from tektiv. if you want to show a dashed line too use this code in the same spot.

(chartjs 2.7.2 around line 16289):

            if (opts.labels && opts.labels.usepointstyle) {
                // chartjs code
            } else if (opts.labels && opts.labels.uselinestyle) {
                if (legenditem.borderdash) {
                    ctx.setlinedash(legenditem.borderdash);
                }
                ctx.beginpath();
                ctx.moveto(x, y + fontsize / 2);
                ctx.lineto(x + boxwidth, y + fontsize / 2);
                ctx.stroke();
            } else {
                // chartjs code
            }

score:12

i was able to use pointstyle: line, in the dataset and then under options use labels: {usepointstyle: true,},

score:16

note: this solution only works if you have a local version of chart.js since it needs to edit a function in the source code of the library, which can't be done if you import it form a cdn.

to achieve what you want, you will need to edit the drawlegendbox function (link to source here).

first, as if you wanted to do a pointstyle legend, add the uselinestyle and set it to true like this :

options: {
    legend: {
        labels : {
            uselinestyle: true
        }
    }
}

then you need to go to your local version of chart.js (obvisouly, you cannot edit it if you import it from a cdn) and search for the function drawlegendbox (on chart.js v2.2.1, it is roughly line 6460; in chart.js v2.9.4 search for labelopts && labelopts.usepointstyle).

scroll down a little bit to see something like this :

if (opts.labels && opts.labels.usepointstyle) {
    // recalulate x and y for drawpoint() because its expecting
    // x and y to be center of figure (instead of top left)
    var radius = fontsize * math.sqrt2 / 2;
    var offset = radius / math.sqrt2;
    var centerx = x + offset;
    var centery = y + offset;

    // draw pointstyle as legend symbol
    chart.canvashelpers.drawpoint(ctx, legenditem.pointstyle, radius, centerx, centery);
}
// --- new condition goes here ---
else {
    // draw box as legend symbol
    ctx.strokerect(x, y, boxwidth, fontsize);
    ctx.fillrect(x, y, boxwidth, fontsize);
}

and add this between the two conditions :

else if (opts.labels && opts.labels.uselinestyle) {
    ctx.beginpath();
    ctx.moveto(x, y + fontsize * 0.45);
    ctx.lineto(x + boxwidth, y + fontsize * 0.45);
    ctx.stroke();
}

with this edit, everytime you will set uselinestyle to true, legend boxes will be drawn as lines, as the following screenshot :

enter image description here


Related Query

More Query from same tag