I want to paint a horizontal bar with Chart.js, but i want a default background color (Which is the max value) and paint the current value with another color. Just like the image below. How can i do this?
Single bar with background Chart.js
7.5k views Asked by JaviSanchezG At
2
There are 2 answers
0
On
In addition to @Tarek's answer,
If you need to get the percentage value in the bar,
https://jsfiddle.net/akshaykarajgikar/bk04frdn/53/
Dependensies:
https://chartjs-plugin-datalabels.netlify.app/
var bar_ctx = document.getElementById('bar-chart');
var bar_chart = new Chart(bar_ctx, {
type: 'horizontalBar',
data: {
labels: [],
datasets: [{
data: [57.866],
backgroundColor: "#00BC43",
datalabels: {
color: 'white' //Color for percentage value
}
}, {
data: [100 - 57.866],
backgroundColor: "lightgrey",
hoverBackgroundColor: "lightgrey",
datalabels: {
color: 'lightgray' // Make the color of the second bar percentage value same as the color of the bar
}
}, ]
},
options: {
legend: {
display: false
},
tooltips: {
enabled: false
},
scales: {
xAxes: [{
display: false,
stacked: true
}],
yAxes: [{
display: false,
stacked: true
}],
}, // scales
plugins: { // PROVIDE PLUGINS where you can specify custom style
datalabels: {
align: "start",
anchor: "end",
backgroundColor: null,
borderColor: null,
borderRadius: 4,
borderWidth: 1,
font: {
size: 20,
weight: "bold", //Provide Font family for fancier look
},
offset: 10,
formatter: function(value, context) {
return context.chart.data.labels[context.dataIndex]; //Provide value of the percentage manually or through data
},
},
},
}, // options
});
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]"></script>
<canvas id="bar-chart" height="20"></canvas>
There is no easy way to do this in Chart.js (such as a specific "100% stacked bar" type). What you need is two stacked horizontal bars.
First, define your chart-type as a
horizontalBar
In order to have a single bar instead of two, they need to be stacked. You also need to hide the scales. Optionally, you can hide the legend and the tooltip. This is all configured in the options:
As stacked bars are placed on top of each other, your first dataset contains your value (57.866), and the second dataset corresponds to
max - value
. Here's an example consideringvalue = 57866
andmax = 80000
:Here's the jsfiddle with the full code.