我有一個水平條形圖,我想要的結果就像這張使用Chartjs庫的照片
這是以下代碼:
TS:
createAreaChart() {
this.barChart1 = document.getElementById('barChart1');
this.ctx1 = this.barChart1.getContext('2d');
let i = 0;
this.data1.forEach(div => {
if(i==0){
this.backgroundColors.push('#A60A2D');
} if(i==1) {
this.backgroundColors.push('#00A2C3');
} if(i==2) {
this.backgroundColors.push('#434F55');
i = -1;
}
i ;
});
this.chart1 = new Chart(this.ctx1, {
type: 'horizontalBar',
data: {
labels: this.data1.map(r => r.icon),
datasets: [{
data: this.data1.map(r => r.total),
label: 'Annual Cost',
backgroundColor: this.backgroundColors,
borderColor: this.backgroundColors,
borderWidth: 1
}]
},
options: {
legend: {
display: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var value = data.datasets[0].data[tooltipItem.index];
if (parseInt(value) >= 1000) {
return '$' value.toFixed(2).toString().replace(/\B(?=(\d{3}) (?!\d))/g, ",");
} else {
return '$' value.toFixed(2).toString();
}
}
}
},
scales: {
yAxes: [{
ticks: {
beginAtZero: true,
precision: 2,
userCallback : function(value, index, values) {
if(parseInt(value) >= 1000){
return '$' value.toString().replace(/\B(?=(\d{3}) (?!\d))/g, ",");
} else {
return '$' value;
}
}
}
}]
}
}
});
this.chart1.height = 225;
}
HTML
<div >
<div >
<div >Test</div>
</div>
<div >
<div >
<canvas id="barChart1" height="220px"></canvas>
</div>
</div>
</div>
結果
我需要將 Y 軸文本放在每個條形上方,我該如何實作?
作為我嘗試使用的其他答案:
layout: {
padding: {
left: 0,
right: 0,
top: 15,
bottom: 0
}
}
或者
plugins: {
datalabels: {
anchor: 'end',
align: 'top',
formatter: Math.round,
font: {
weight: 'bold'
}
}
}
但它不起作用,我需要做什么才能達到預期的結果?
uj5u.com熱心網友回復:
這主要可以通過選項的不同選項來完成scales.yAxes.ticks。
有關更多詳細資訊,請參閱Chart.js v2.9.4 檔案中的刻度配置。
請看看下面的可運行代碼,看看它是如何作業的。
new Chart('myChart', {
type: 'horizontalBar',
data: {
labels: ['One', 'Two', 'Three'],
datasets: [{
data: [8, 12, 7],
backgroundColor: ['#A60A2D', '#00A2C3', '#434F55'],
barPercentage: 0.6
}]
},
options: {
responsive: false,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines: {
drawOnChartArea: false
},
ticks: {
min: 0
}
}],
yAxes: [{
gridLines: {
display: false
},
ticks: {
mirror: true,
fontSize: 18,
labelOffset: -22
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" height="200"></canvas>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/320966.html
上一篇:角度防止用戶多次提交
