我在我的angular7应用程序中使用chartjs 2.8.0版本。在我的组件模板中,我添加了以下格式的图表条形图。
<div class="row">
<div class="col-12" style="width: 100%; overflow-x: auto;">
<canvas [hidden]="listView" id="barChart" height="100"></canvas>
</div>
</div>
在我的组件中,创建了图表实例。在初始化时,我创建了一个空图表,当获得API结果时,我使用数据更新了图表。我还在图形中每个条形的顶部显示标签。我的问题是,当条数增加时,条上的标签会损坏。如何在条形图中添加水平滚动并为每个条保持固定的宽度?
this.barChart = new Chart('barChart', {
type: 'bar',
data: {
labels: [],
datasets: [
{
data: [],
backgroundColor: [],
borderColor: [],
borderWidth: 1
}
]
},
options: {
title: {
display: true,
text: 'No Data Found',
fontSize: 18
},
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
display: false,
color: 'grey',
drawBorder: true
}
}],
yAxes: [{
gridLines: {
display: false,
color: 'grey',
drawBorder: true
},
ticks: {
beginAtZero: true,
fontColor: '#000',
}
}]
},
hover: {
animationDuration: 0
},
animation: {
duration: 1,
onComplete: function () {
console.log('this', this);
const chartInstance = this.chart;
const ctx = chartInstance.ctx;
ctx.font = Chart.helpers.fontString(Chart.defaults.global.defaultFontSize,
Chart.defaults.global.defaultFontStyle, Chart.defaults.global.defaultFontFamily);
ctx.textAlign = 'center';
ctx.textBaseline = 'bottom';
this.data.datasets.forEach(function (dataset, i) {
const meta = chartInstance.controller.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
const data = dataset.data[index];
console.log('bar', data);
ctx.fillStyle = '#000';
ctx.fontStyle = 'bold';
ctx.font = 'bold ' + bar._model.height / 2 + 'px Arial';
ctx.fillText('100%', bar._model.x, bar._model.y + 20);
ctx.fillText(data.billaBle === 1 ? 'Billable' : 'Non Billable', bar._model.x, bar._model.y + 35);
});
});
}
},
}
});
}