I would like to create a time line like this: [1]: https://i.stack.imgur.com/RQ819.png
But I don’t understand how to put green into the top bar and yellow into the bottom bar.
This is what I got so far but I don’t find anything how to make group only for one bar.
JavaScript
x
52
52
1
// Set Up
2
const labels = ["ONLINE", "IDLE"];
3
const data = {
4
labels: labels,
5
datasets: [
6
{
7
label: "ONLINE",
8
data: [
9
["2022-01-01", "2022-01-02"],
10
["2022-01-03", "2022-01-04"],
11
],
12
backgroundColor: ["green"],
13
},
14
{
15
label: "IDLE",
16
data: [
17
["2022-01-02", "2022-01-03"],
18
["2022-01-04", "2022-01-05"],
19
],
20
backgroundColor: ["orange"],
21
},
22
],
23
};
24
25
// Config
26
const config = {
27
type: "bar",
28
data: data,
29
options: {
30
responsive: true,
31
indexAxis: "y",
32
scales: {
33
xAxis: {
34
min: "2022-01-01",
35
type: "time",
36
time: {
37
unit: "day",
38
},
39
40
ticks: {
41
display: false,
42
},
43
},
44
yAxes: {
45
stacked: true,
46
beginAtZero: true,
47
},
48
},
49
},
50
};
51
// Render Chart
52
const myChart = new Chart(document.getElementById("myChart"), config);
JavaScript
1
8
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
2
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
3
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
4
5
6
<div>
7
<canvas id="myChart"></canvas>
8
</div>
Advertisement
Answer
You need to define a separate datasets
for each floating bar.
Please take a look at your amended code and see how it works.
JavaScript
1
47
47
1
const data = {
2
labels: ["ONLINE", "IDLE"],
3
datasets: [{
4
label: "Jan 1 - Jan 2",
5
data: [["2022-01-01", "2022-01-02"],],
6
backgroundColor: "green"
7
},
8
{
9
label: "Jan 2 - Jan 3",
10
data: [,["2022-01-02", "2022-01-03"]],
11
backgroundColor: "orange"
12
},
13
{
14
label: "Jan 3 - Jan 4",
15
data: [["2022-01-03", "2022-01-04"],],
16
backgroundColor: "green"
17
},
18
{
19
label: "Jan 4 - Jan 5",
20
data: [,["2022-01-04", "2022-01-05"]],
21
backgroundColor: "orange"
22
}
23
]
24
};
25
26
const config = {
27
type: "bar",
28
data: data,
29
options: {
30
responsive: true,
31
indexAxis: "y",
32
scales: {
33
x: {
34
min: "2022-01-01",
35
type: "time",
36
time: {
37
unit: "day"
38
}
39
},
40
y: {
41
stacked: true
42
}
43
}
44
}
45
};
46
47
const myChart = new Chart("myChart", config);
JavaScript
1
7
1
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
2
<script src="https://cdn.jsdelivr.net/npm/chart.js/dist/chart.min.js"></script>
3
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-date-fns/dist/chartjs-adapter-date-fns.bundle.min.js"></script>
4
5
<div>
6
<canvas id="myChart"></canvas>
7
</div>