I'm trying to dynamically add a label to my line chart depending on the number of points coming back from the database. I have a table which, once the user clicks on a particular row, updates the chart. The number of point can vary. ie chart 1 has 2 points & chart 2 has 5 points. I need to count the number of points and display the bottom label in a sequential number order. ie 0, 1 for chart 1 and 0, 1, 2, 3, 4 for chart 2. The image below shows what I want to avoid happening. 2, 3 & 4 should not be showing in chart 1 but showing in chart 2.
I've hard coded the label data for this example [0, 1, 2, 3, 4]. xAxisValue.length brings back the number of points each chart displays. Appreciate any help.
data={{
labels: [0, 1, 2, 3, 4],
datasets: [
{
label: 'Training',
data: yAxisValue,
fill: false,
borderColor: 'rgb(0, 119, 182)',
backgroundColor: 'rgb(0, 119, 182)',
lineTension: 0,
},
{
label: 'Validation',
data: xAxisValue,
fill: false,
borderColor: 'rgb(0, 180, 216)',
backgroundColor: 'rgb(0, 180, 216)',
lineTension: 0,
},
],
}}
You can define a xAxes.ticks.callback
function. It should return the label
when a corresponding data
value exists, null
otherwise.
xAxes: [{
ticks: {
callback: (v, i) => i + 1 <= trainingData.length ? v : null
}
}]
Please take a look at the following runnable code and see how it works.
const trainingData = [0.68, 0.9]; const validationData = [0.57, 0.97]; new Chart('line-chart', { type: 'line', data: { labels: [0, 1, 2, 3, 4], datasets: [{ label: 'Training', data: trainingData, fill: false, borderColor: 'rgb(0, 119, 182)', backgroundColor: 'rgb(0, 119, 182)', lineTension: 0, }, { label: 'Validation', data: validationData, fill: false, borderColor: 'rgb(0, 180, 216)', backgroundColor: 'rgb(0, 180, 216)', lineTension: 0, } ] }, options: { scales: { yAxes: [{ ticks: { min: 0, max: 1 } }], xAxes: [{ ticks: { callback: (v, i) => i + 1 <= trainingData.length? v: null } }] } } });
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script> <canvas id="line-chart" height="90"></canvas>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.