๐:0
Solution:
var ctx = document.getElementById("myChart");
var chartStatus = Chart.getChart("myChart");
if (chartStatus != undefined) {
chartStatus.destroy();
}
var myChart = new Chart(ctx, {
type: "bar",
data: {
labels: ["Cats", "Dogs", "Dugs", "Mice", "Hamster", "Tiger"],
datasets: [
{
label: false,
data: [-9, 1, 9, -9, 1, 9],
// data: [12, 19, -3],
backgroundColor: [
"rgba(39, 152, 228, 0.7)",
"rgba(233, 85, 59, 0.7)",
"rgba(152, 140, 202, 0.7)",
"rgba(39, 152, 228, 0.7)",
"rgba(233, 85, 59, 0.7)",
"rgba(152, 140, 202, 0.7)"
],
borderColor: [
"rgba(39, 152, 228,1)",
"rgba(233, 85, 59, 1)",
"rgba(152, 140, 202, 1)",
"rgba(39, 152, 228,1)",
"rgba(233, 85, 59, 1)",
"rgba(152, 140, 202, 1)"
],
borderWidth: 6
}
]
},
options: {
animation: {
duration: 1,
// https://github.com/jtblin/angular-chart.js/issues/605
onComplete: function () {
var chart = this;
var ctx = chart.ctx;
ctx.font = Chart.helpers.fontString(
Chart.defaults.font.size,
Chart.defaults.font.style,
Chart.defaults.font.family
);
ctx.textAlign = "left";
ctx.textBaseline = "censter";
var labels = this.data.labels;
this.data.datasets.forEach(function (dataset, i) {
var meta = chart.getDatasetMeta(i);
meta.data.forEach(function (bar, index) {
var data = dataset.data[index];
let posx;
if (data < 0) {
posx = bar.x + bar.$context.element.width + 10;
ctx.textAlign = "left";
} else {
posx = bar.x - bar.$context.element.width - 10;
ctx.textAlign = "right";
}
// posx = bar.x;
ctx.fillText(`${labels[index]} (${data})`, posx, bar.y + 3);
});
});
}
},
responsive: true,
indexAxis: "y",
plugins: {
title: {
display: true,
text: "Pets",
font: {
size: 22
}
},
legend: {
display: false
},
tooltip: {
enabled: false
}
},
scales: {
x: {
grid: {
display: false,
drawBorder: false,
drawOnChartArea: false,
drawTicks: false
},
labels: {
display: false
},
min: -20,
max: 20,
ticks: {
color: "#d6d6d9",
font: {
size: 22
}
}
},
y: {
grid: {
display: false,
drawBorder: false,
drawOnChartArea: false,
drawTicks: false
},
labels: ["Text1", "Text2", "Text3", "Text4", "Text5", "Text6"],
gridLines: {
display: false
},
barPercentage: 1,
ticks: {
color: "#d6d6d9",
font: {
size: 22
}
}
},
secondY: {
labels: ["Text7", "Text8", "Text9", "Text10", "Text11", "Text12"],
position: "right",
grid: {
display: false,
drawBorder: false,
drawOnChartArea: false,
drawTicks: false
},
ticks: {
color: "#d6d6d9",
font: {
size: 22
}
}
}
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.min.js" integrity="sha512-QSkVNOCYLtj73J4hbmVoOV6KVZuMluZlioC+trLpewV8qMjsWqlIQvkn1KGX2StWvPMdWGBqim1xlC8krl1EKQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<canvas id="myChart"></canvas>