首页 > 解决方案 > 在 chart.js 条形图中,如何标记类别中的每个条形?

问题描述

如何标记 chart.js 条形图类别中的每个条形?

我有 1 个类别,该类别中有 2 个条形图。我在条形图上使用渐变,这些只能应用于单个类别中的条。

options = {
        scales: {
            yAxes: [{
                ticks: {
                    beginAtZero: true
                }
            }],
            xAxes: [{
                ticks: {
                    callback: (value, index, values) => {
                        console.log(value, index, values);
                    }
                }
            }]
        }
}

let ctx = this.bar.nativeElement.getContext('2d');

    let grad1 = ctx.createLinearGradient(0, 0, 0, 200);
    grad1.addColorStop(0, 'rgb(105,130,231)');
    grad1.addColorStop(1, 'rgb(125,222,238)');

    let grad2 = ctx.createLinearGradient(0, 0, 0, 200);
    grad2.addColorStop(0, 'rgb(233,105,210)');
    grad2.addColorStop(1, 'rgb(247,126,151)');

    this.barColors.push({backgroundColor: grad1, hoverBackgroundColor: grad1});
    this.barColors.push({backgroundColor: grad2, hoverBackgroundColor: grad2});

HTML:

<canvas #bar baseChart
        [datasets]="plotData"
        [labels]="l"
        [options]="options"
        chartType="bar"
        [colors]="barColors"
        (chartClick)="chartClicked($event)">
</canvas>

标签: javascriptchart.js

解决方案


1) 为一个类别中的每个子类别设置 2 个标签 2) 为一个类别中的每个条形图,如果它与标签位置匹配,则添加该值,然后为与标签位置不匹配的替代子类别的值添加 0

这将生成一个条形图,其中每个类别只有 1 个该子类别独有的颜色渐变条。

您可能需要调整条形大小,因为我只有 2 个子类别,我设置

scales: {
        xAxes: [{
            barPercentage: 8,
            categoryPercentage: 0.1
        }]
    }
}

它与我的类别标签非常接近。


推荐阅读