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

时间:2019-03-26 12:42:55

标签: javascript 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>

1 个答案:

答案 0 :(得分:0)

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

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

由于我只设置了2个子类别,因此您可能需要尝试调整条的大小

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

对我来说,它与类别标签非常接近。

相关问题