Chart.js中折线图的图例

Joe*_*nek 7 chart.js

我想为行数据自定义图例,以便图例图形是一条线(样式与实际数据线相似)而不是一个框.

据我可以告诉从源,图形可以是一个点或一个框和框的高度被固定到的字体大小.'generateLabels'选项似乎不允许扩展这些约束.

版本2.2.1.

谢谢你的帮助.

tek*_*tiv 14

此解决方案仅在您具有本地版本的Chart.js时才有效,因为它需要在库的源代码中编辑函数,如果从CDN导入它,则无法执行此操作.

要实现您想要的功能,您需要编辑drawLegendBox功能(此处链接到源代码).

首先,好像你想要做一个pointStyle图例,添加并将其useLineStyle设置为true如下所示:

options: {
    legend: {
        labels : {
            useLineStyle: true
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你需要转到本地版本的Chart.js(显然,如果从CDN导入它就无法编辑它)并搜索该函数drawLegendBox(在Chart.js v2.2.1上,它大致是6460行).

向下滚动一下,看看这样的东西:

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);
}
Run Code Online (Sandbox Code Playgroud)

并在两个条件之间添加:

else if (opts.labels && opts.labels.useLineStyle) {
    ctx.strokeRect(x, y + fontSize / 2, boxWidth, 0);
}
Run Code Online (Sandbox Code Playgroud)

通过此编辑,每次设置useLineStyle为true时,图例框都将绘制为线条,如下面的屏幕截图所示:

在此输入图像描述


小智 12

我能够line在数据集中使用 pointStyle: ,然后在选项下使用标签:{usePointStyle: true,}