I want to create a horizontal bar chart like this photo using
So I follow the instructions and I have something like:
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: 'bar',
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 class="card chart-card">
<div class="card-header">
<div class="card-title">Test</div>
</div>
<div class="card-body">
<div class="chart">
<canvas id="barChart1" height="220px"></canvas>
</div>
</div>
</div>
But for some reason I get a vertical bar like this:
How can I do to change it to be horizontally orientation, the current Y axis be at X axis and above each bar use current X axis, exactly like the first photo? Regards
UPDATE
As the comment below I currently using
Now, I need to place Y axis text above each bar, is this possible?
CodePudding user response:
It seems that you're still using Chart.js version 2
. The current latest version is 3.5.1
.
Change type: 'bar'
into type: 'horizontalBar'
and it should work.
new Chart(this.ctx1, {
type: 'horizontalBar',
...
For further details, please consult Horizontal Bar Chart from the
Chart.js v2.9.4
documentation.
CodePudding user response:
Add this:
options: {
indexAxis: 'y',
...
}
Here is ChartJS documentation