Reputation: 1005
I am trying to change the color of a part of a line chart in chart.js. I followed these posts:
How to change line segment color of a line graph in Chart.js?
And
I am close to achieving the proper result, however, the second line does not want to begin at the end of the first one.
Here is the code that is problematic:
var myChart5 = new Chart(ctx5, {
type: 'line',
data: {
labels: document.getElementById('tag4').textContent == 'ITEMS IN DIFFICULTY' ?
['90 days backward','60 days backward','30 days backward','30 days forward'] :
['90 days backward','60 days backward','30 days backward','30 days forward'],
datasets: [{
labels: labels8,
data: defaultData8,
fill: true,
backgroundColor: ['rgba(54, 162, 235, 0.2)'],
borderColor: ['rgba(255, 99, 132, 1)'],
borderWidth: 1
}, {
label: labels18,
data: defaultData18,
fill: true,
backgroundColor: ['rgba(255, 99, 132, 0.2)'],
borderColor: ['rgba(255, 99, 132, 1)'],
borderWidth: 1
}],
options: {
scales: {
yAxes: [{
scaleLabel: {
display: true,
labelString: 'Quantity Sold'
},
ticks: {
min: 0
}
}]
}
}
}
});
And here is what the data looks like:
"labels8": [
"90_days_backward",
"60_days_backward",
"30_days_backward"
],
"default8": [
129259.0,
149651.0,
70699.0
],
"labels18": [
"30_days_backward",
"30_days_forward"
],
"default18": [
70699.0,
109145.6
]
I am a bit confused about how to proceed, I have tried include "NaN" values in the second dataset to push it forward but it won't make the trick. Would someone has a clue on how to fix this problem?
Upvotes: 2
Views: 603
Reputation: 5283
In order for the second line to start at the end of the first, its data array needs to skip those values. What you can do is fill the second array with null
as many times as the first array has values.
In your chart configuration pasted above, in the second dataset, here is how you can assign the data
property:
// to start right after the end of the previous line
data: defaultData8.slice().fill(null).concat(defaultData18)
// to start on top of the end of the previous line
data: defaultData8.slice(1).fill(null).concat(defaultData18)
This will copy the first data array (too keep the original intact), override all its values with null
, the concatenate it with second like data, then assign it to the data
property of the second dataset.
Upvotes: 2