How to draw multiple color bars in a bar chart along a Horizontal Line using chart.js
I am making a chart using chart.js in react environment.
If you look at the second image, what if there is 130% along the Horizontal Line? 100
is formed with gray
and above 100 green
. I also want to make it in the same format as above.
I've been looking for it for 2 days, but I don't know how to do it
This is my work in progress.
I want to make it in this format.
This is my code.
import { Bar, Chart } from 'react-chartjs-2';
import annotationPlugin from "chartjs-plugin-annotation";
import "chartjs-plugin-datalabels";
import ChartDataLabels from "chartjs-plugin-datalabels";
Chart.register([annotationPlugin], [ChartDataLabels] );
let chartColors = {
yellow: '#F4D068',
green: '#4CC26F',
gray: '#EBEBEB'
};
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June'],
datasets: [
{
label: 'My First dataset',
backgroundColor: [],
borderColor: '#EBEBEB',
borderWidth: 1,
borderRadius: 10,
data: [65, 140, 130, 200, 56, 35, 80],
random: ['Check', 'Out', 'Udemy', 'Course', 'Charjs 3', 'Coming Out', 'Next week'],
},
],
};
let colorChangeValue = 100;
let dataset = data.datasets[0];
for (let i = 0; i < dataset.data.length; i++) {
if (dataset.data[i] > colorChangeValue) {
dataset.backgroundColor[i] = chartColors.green;
if (dataset.data[i] < 100) {
dataset.backgroundColor[i] = chartColors.gray;
}
}
if (dataset.data[i] < colorChangeValue) {
dataset.backgroundColor[i] = chartColors.yellow;
}
}
return (
<Bar
data={data}
width={100}
height={70}
options={{
scales: {
x: {
stacked: true,
grid: {
display: false,
},
},
y: {
stacked: true,
grid: {
},
ticks: {
maxTicksLimit: 1
}
}
},
plugins: {
legend: {
display: false
},
title: {
display: true,
text: "범례1",
padding: {
bottom: 30
},
weight: "bold",
color: "#00325c",
font: {
size: 13
},
align: "start"
},
datalabels: {
display: true,
color: "black",
anchor: 'end',
align: 'top',
formatter: function (value) {
return "\n" + value + "%";
}
}
},
annotations: {
myHorizontalLine: {
type: "line",
scaleID: "y",
borderWidth: 3,
borderColor: "#333333",
value: 100,
borderDash: [8, 8],
label: {
font: {
weight: "normal"
},
rotation: "auto",
enabled: true
}
},
}
}}
/>
)
Solution 1:
You could define a second dataset that does nothing but drawing the gray space up to the limit of 100.
{
backgroundColor: '#DDD',
hoverBackgroundColor: '#DDD',
data: [100, 0, 0, 0, 100, 100],
datalabels: {
display: false
}
},
Also make sure that only the x-axis has the option stacked: true
.
Together with this, you'll also need to adjust some other options. A tooltip.filter
for example will prevent Chart.js from showing a tooltip for the second dataset.
tooltip: {
filter: tooltipItem => !tooltipItem.datasetIndex
},
Please take a look at the StackBlitz with your amended code and see how it works.