I am using chart.js to display some data in the line chart. It's working fine except for one thing that why it's showing an extra line as highlighted by me in the attachment below:
I'm providing just one dataset like that:
It will show you a tooltip on hover on one line but it's showing nothing while hovering on the second line. Plz, tell me a way to remove that second line and tell me why it's showing.
Here is the codepen link
Here is the code, plz wait for some seconds after running the below code because it is fetching the data from api.
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: ["2016-01-01T00:00:00Z", "2017-01-01T00:00:00Z", "2018-01-01T00:00:00Z", "2019-01-01T00:00:00Z", "2020-01-01T00:00:00Z", "2021-01-01T00:00:00Z", "2022-01-01T00:00:00Z",],
datasets: [{
label: 'Demo',
data: [],
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
],
//borderWidth: 0.2
}]
},
options: {
scales: {
xAxes: [{
type: 'time',
time: {
unit: 'year' //show year on x-axis
}
}],
yAxes: [ //show y-axis on right side
{
display: true,
position: 'right',
ticks: {
//beginAtZero: true
}},
{
display: false,
position: 'left',
}
]
},
responsive: true,
maintainAspectRatio: false,
elements: {
line: {
fill: false,
borderWidth: 2,
},
point:{
radius: 0
}
}
}
});
function addData(chart, data) {
//chart.data.labels.push(label);
chart.data.datasets[0].data=data;
// chart.data.datasets.forEach((dataset) => {
// dataset.data=data;
// });
chart.update();
}
$(document).ready(function(){
$.ajax({
url:'https://yfinance-backend.herokuapp.com/historical-data/sp500/',
type:'get',
data:{},
success:function(response,status,xhr){
let chart_data=[];
response.forEach(function(record, index){
let obj={};
obj.t=record.date;
obj.y=record.close_value;
chart_data.push(obj);
});
console.log(chart_data);
addData(myChart, chart_data);
},
error:function(xhr,status,errorThrown){},
complete:function(xhr,status){
var response=xhr.responseJSON;
}
});
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>

