Chart.js chart not displaying until I open the browser's console - javascript

I was trying to create a simple chart that displays covid-19 data with chart.js, but for some reason the code I wrote up was not working. The chart is empty upon loading the page, but if I open up the browser's console, the data suddenly shows up. And if I load the page with the console open, the chart is still empty, but if I close the console, the chart is filled.
Here is what it looks like upon loading the page with the console open: empty chart
And here is what it looks like immediately after I close the console: filled chart
The following is all the code I used:
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Playing with Covid19 data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.0/css/bulma.min.css">
</head>
<body>
<canvas id="deathChart" width="100" height="50"></canvas>
<script>
const api_url = "https://covidtracking.com/api/us/daily"
let dates = [],
deaths =[],
hospitalizations = [],
negatives = [],
positives = [],
recoveries = [],
onVentilatorCurrently_list = []
function getData()
{
console.log("About to fetch the data")
fetch(api_url)
.then(response => response.json())
.then(data => {
for(let row of data){
let {date, death, hospitalized, negative, onVentilatorCurrently, positive, recovered} = row
dates.splice(0, 0, date)
deaths.splice(0, 0, death)
hospitalizations.splice(0, 0, hospitalized)
negatives.splice(0, 0, negative)
onVentilatorCurrently_list.splice(0, 0, onVentilatorCurrently)
positives.splice(0, 0, positive)
recoveries.splice(0, 0, recovered)
}
console.log("Finished fetching the data")
})
}
getData()
let death_config = {
type: 'line',
data:
{
labels: dates,
datasets: [
{
label: "Deaths from Covid-19",
data: deaths,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1
}
]
},
options: {
tooltips: {
mode: "index",
intersect: false,
},
}
}
let death_ctx = document.getElementById('deathChart').getContext('2d')
let deathChart = new Chart(death_ctx, death_config)
</script>
</body>

So I think you are loading the data before the chart is finished rendering. When you open/close the console it is resizing the window which triggers a re-render and shows the data properly. You can fix this by creating the chart after the data is done loading.
Edit: Changed to call chart.update() per OP's request.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Playing with Covid19 data</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.0/css/bulma.min.css">
</head>
<body>
<canvas id="deathChart" width="100" height="50"></canvas>
<script>
const api_url = "https://covidtracking.com/api/us/daily"
let dates = [],
deaths = [],
hospitalizations = [],
negatives = [],
positives = [],
recoveries = [],
onVentilatorCurrently_list = []
function getData(chart) {
console.log("About to fetch the data")
fetch(api_url)
.then(response => response.json())
.then(data => {
for (let row of data) {
let {
date,
death,
hospitalized,
negative,
onVentilatorCurrently,
positive,
recovered
} = row
dates.splice(0, 0, date)
deaths.splice(0, 0, death)
hospitalizations.splice(0, 0, hospitalized)
negatives.splice(0, 0, negative)
onVentilatorCurrently_list.splice(0, 0, onVentilatorCurrently)
positives.splice(0, 0, positive)
recoveries.splice(0, 0, recovered)
}
console.log("Finished fetching the data")
chart.update();
})
}
let death_config = {
type: 'line',
data: {
labels: dates,
datasets: [{
label: "Deaths from Covid-19",
data: deaths,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1
}]
},
options: {
tooltips: {
mode: "index",
intersect: false,
},
}
}
let death_ctx = document.getElementById('deathChart').getContext('2d')
let deathChart = new Chart(death_ctx, death_config)
getData(deathChart);
</script>
</body>

Check
const api_url = "https://covidtracking.com/api/us/daily";
let dates = [],
deaths =[],
hospitalizations = [],
negatives = [],
positives = [],
recoveries = [],
onVentilatorCurrently_list = []
function getData(){
console.log("About to fetch the data")
fetch(api_url)
.then(response => response.json())
.then(data => {
for(let row of data){
let {date, death, hospitalized, negative, onVentilatorCurrently, positive, recovered} = row
dates.splice(0, 0, date)
deaths.splice(0, 0, death)
hospitalizations.splice(0, 0, hospitalized)
negatives.splice(0, 0, negative)
onVentilatorCurrently_list.splice(0, 0, onVentilatorCurrently)
positives.splice(0, 0, positive)
recoveries.splice(0, 0, recovered)
}
console.log("Finished fetching the data")
})
}
getData()
let death_config = {
type: 'line',
data:
{
labels: dates,
datasets: [
{
label: "Deaths from Covid-19",
data: deaths,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.5)',
borderWidth: 1
}
]
},
options: {
tooltips: {
mode: "index",
intersect: false,
responsive: true,
maintainAspectRatio: true
},
}
}
let death_ctx = document.getElementById('deathChart').getContext('2d')
let deathChart = new Chart(death_ctx, death_config)
setTimeout(function() { deathChart.update(); },1000);
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma#0.9.0/css/bulma.min.css">
<div><canvas id="deathChart" width="100" height="50"></canvas></div>

Related

How to use ChartjsPluginStacked100 javascript only, no typescript

good day. Im trying to use the plugin chartjs-plugin-stacked100 with chart.js vs3 but im not having any luck. it stays as normal stacked horizontal bar chart.
I think im doing something wrong when importing or registering i but not know what im doing wrong.
here is how im doing my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js#3.0.0/dist/chart.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-plugin-stacked100#1.0.0"></script>
</head>
<body>
<div id="my-chart-container" style="height:400px;">
<canvas id="my-chart" ></canvas>
</div>
<script src="./index.js" type="module"></script>
</body>
</html>
and here is how im doing my js:
Chart.register(ChartjsPluginStacked100);
new Chart(document.getElementById("my-chart"), {
type: "bar",
data: {
labels: ["2010-2015", "2016", "2017", "2018", "2019"],
datasets: [
{ label: "IG", data: [0, 250, 7417.5, 650, 1455], backgroundColor: "rgba(244, 143, 177, 0.6)" },
{ label: "HY", data: [0, 0, 0, 1000, 0], backgroundColor: "rgba(255, 235, 59, 0.6)" },
{ label: "NR", data: [0, 675, 4182.5, 1505, 1735], backgroundColor: "rgba(100, 181, 246, 0.6)" }
]
},
options: {
indexAxis: 'y',
scales: {
xAxis:{
stacked:true
},
yAxis:{
stacked:true
},
},
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
const datasetIndex = tooltipItem.datasetIndex;
const datasetLabel = data.datasets[datasetIndex].label;
// You can use two type values.
// `data.originalData` is raw values,
// `data.calculatedData` is percentage values, e.g. 20.5 (The total value is 100.0)
const originalValue = data.originalData[datasetIndex][tooltipItem.index];
const rateValue = data.calculatedData[datasetIndex][tooltipItem.index];
return `${datasetLabel}: ${rateValue}% (raw ${originalValue})`;
}
}
},
plugins: {
plugins:[ChartDataLabels],
stacked100: { enable: true, replaceTooltipLabel: false }
}
}
});
if anyone can guide me to do it correctly would be appreciated.
here is a jsbin with it, example
Thanks for your time.

Code doesn't work after updating chart.js versioning

I have this great code working here where I load the data in from an external file called test.csv.
Everything works great until I try to update the chart.js library link.
Can anyone tell me why this code doesn't work with more current versions of chart.js?
I want to update it so that I can install the plugin that lets you show the charts values. Alternatively some code that would facilitate this would work great as well!
Appreciate any help!
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Data project</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div class="wrapper">
<h1>MY CHART</h1>
<h2>This is the subhead for my chart </h2>
<canvas id="myChart" width="350" height="250" style="background-color:white;"></canvas>
</div>
<script>
window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: dollar.years,
datasets: [
{
label: 'Voter support (%)',
data: dollar.vals,
backgroundColor: [
'#134D85',
'#134D85',
'#134D85',
'#134D85',
'#134D85',
],
}]
},
options: {
layout: {
padding: {
left: 0,
right: 0,
top: 8,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: true,
position: 'top',
usePointStyle: true,
padding: 1,
labels: {
boxWidth: 15,
}
},
scales: {
yAxes: [{
gridlines: {
display: true,
color: '#ffffff',
zeroLineColor: '#ffffff',
}
}],
xAxes: [{
gridLines: {
display: true,
drawOnChartArea: false
},
}],
}
}
});
}
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('data/test.csv');
var data = await response.text();
data = data.replace(/"/g, "");
var years = [];
var vals = [];
var rows = data.split('\n').slice(1);
rows = rows.slice(0, rows.length - 1);
rows = rows.filter(row => row.length !== 0)
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
vals.push(0 + parseFloat(cols[1]));
});
console.log(years, vals);
return { years, vals };
}
</script>
</body>
</html><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Coding Train: Data and APIs Project 1</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.bundle.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<div class="wrapper">
<h1>MY CHART</h1>
<h2>This is the subhead for my chart </h2>
<canvas id="myChart" width="350" height="250" style="background-color:white;"></canvas>
</div>
<script>
// Data from: https://data.giss.nasa.gov/gistemp/
// Mean from: https://earthobservatory.nasa.gov/world-of-change/DecadalTemp
window.addEventListener('load', setup);
async function setup() {
var ctx = document.getElementById('myChart').getContext('2d');
var dollar = await getData();
var myChart = new Chart(ctx, {
type: 'horizontalBar',
data: {
labels: dollar.years,
datasets: [
{
label: 'Voter support (%)',
data: dollar.vals,
backgroundColor: [
'#134D85',
'#134D85',
'#134D85',
'#134D85',
'#134D85',
],
}]
},
options: {
layout: {
padding: {
left: 0,
right: 0,
top: 8,
bottom: 0
}
},
responsive: true,
title: {
display: false
},
legend: {
display: true,
position: 'top',
usePointStyle: true,
padding: 1,
labels: {
boxWidth: 15,
}
},
scales: {
yAxes: [{
gridlines: {
display: true,
color: '#ffffff',
zeroLineColor: '#ffffff',
}
}],
xAxes: [{
gridLines: {
display: true,
drawOnChartArea: false
},
}],
}
}
});
}
async function getData() {
// const response = await fetch('testdata.csv');
var response = await fetch('data/test.csv');
var data = await response.text();
data = data.replace(/"/g, "");
var years = [];
var vals = [];
var rows = data.split('\n').slice(1);
rows = rows.slice(0, rows.length - 1);
rows = rows.filter(row => row.length !== 0)
rows.forEach(row => {
var cols = row.split(",");
years.push(cols[0]);
vals.push(0 + parseFloat(cols[1]));
});
console.log(years, vals);
return { years, vals };
}
</script>
</body>
</html>```
For a start next time might be a good idea to read the documentation and the migration guide.
Few things that are at least wrong:
Link name has changed to lower case so 2.9.4/Chart.js -> 3.5.0/chart.js
Scales have changed from 2 arrays to objects for each scale:
options: {
scales: {
x: {
// config for default x scale
},
x2: {
// config for second x scale
},
y: {
// config for default y scale
},
}
}
title and legend config have been moved to the plugins section so options.title -> options.plugins.title and options.legend -> options.plugins.legend.
Alternativly you could also just use an older release of the datalabels plugin that has been written for V2
<script src="https://cdnjs.cloudflare.com/ajax/libs/chartjs-plugin-datalabels/1.0.0/chartjs-plugin-datalabels.js"></script>

Chart.js - How to update data

I've created chart that shows temperature from past 20 minute. Data is obtained via GET request from my Thingspeak meteo station. How could I send new request every 10 seconds and update only data in chart.
I think chart.update() would work, but I have no idea how to implement it :/
Here is some code:
chartIt();
async function chartIt(){
const loadedData = await loadData();
var myChart = new Chart(document.getElementById("tempChart").getContext('2d'), {
type: 'line',
backgroundColor: 'rgba(255, 251, 230, 0.5)',
data: {
labels: loadedData.timeStamp,
datasets: [{
label: 'Temperature',
data: loadedData.chartData,
backgroundColor: [
'rgba(255, 0, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
})
}
async function loadData() {
var chartData = [];
var timeStamp = [];
await $.getJSON('https://api.thingspeak.com/channels/214058/fields/1.json?minutes=20', function(data) {
$.each(data.feeds, function(){
var value = this.field1;
var raw_time = this.created_at;
if (value) {
value = (value / 1000) * 1000;
value = parseFloat(value.toFixed(2));
}
if (raw_time){
var timewZ = raw_time.split("T").slice(1);
}
chartData.push(value);
timeStamp.push(timewZ);
});
});
return {chartData, timeStamp};
}
.chartWrapper{
width: 500px;
height: 500px;
margin:auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="chartWrapper">
<canvas id="tempChart"></canvas>
</div>
</body>
<script src="script.js"></script>
</html>
This is simplistic but would do the trick. If you wanted to enable/disable it, you'd want to hang onto your interval so you can kill it... This works though! :)
const updateFreqency = 10000;
chartIt(updateFreqency);
async function chartIt(interval){
const loadedData = await loadData();
var myChart = new Chart(document.getElementById("tempChart").getContext('2d'), {
type: 'line',
backgroundColor: 'rgba(255, 251, 230, 0.5)',
data: {
labels: loadedData.timeStamp,
datasets: [{
label: 'Temperature',
data: loadedData.chartData,
backgroundColor: [
'rgba(255, 0, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
})
setInterval(async () => {
const data = await loadData();
myChart.data.datasets.forEach(d => d.data = data.chartData)
myChart.labels = data.timeStamp
myChart.update()
}, interval)
}
async function loadData() {
var chartData = [];
var timeStamp = [];
await $.getJSON('https://api.thingspeak.com/channels/214058/fields/1.json?minutes=20', function(data) {
$.each(data.feeds, function(){
var value = this.field1;
var raw_time = this.created_at;
if (value) {
value = (value / 1000) * 1000;
value = parseFloat(value.toFixed(2));
}
if (raw_time){
var timewZ = raw_time.split("T").slice(1);
}
chartData.push(value);
timeStamp.push(timewZ);
});
});
return {chartData, timeStamp};
}
.chartWrapper{
width: 500px;
height: 500px;
margin:auto;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<link rel="stylesheet" href="style.css">
<title>Document</title>
</head>
<body>
<div class="chartWrapper">
<canvas id="tempChart"></canvas>
</div>
</body>
<script src="script.js"></script>
</html>
basically you need access to chart so if you move its context/scope to be outside of the function then you can access it from another function....
something like....
ommited some of the code as well this is the core bits..
//moved out
var myChart;
async function chartIt(){
const loadedData = await loadData();
myChart = new Chart(document.getElementById("tempChart").getContext('2d'), {
type: 'line',
backgroundColor: 'rgba(255, 251, 230, 0.5)',
data: {
labels: loadedData.timeStamp,
datasets: [{
label: 'Temperature',
data: loadedData.chartData,
backgroundColor: [
'rgba(255, 0, 132, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)'
],
borderWidth: 1
}]
},
})
}
function myTimer() {
var loadedData = await loadData();
//have access here as it was move out of the function which created it.
myChart.data.labels = loadedData.timeStamp;
myChart.data.datasets = loadedData.chartData;
myChart.update();
}
var myVar = setInterval(myTimer, 10000);

ChartJS: Chart not displaying full range of data

My ChartJS chart is not displaying all the data. This is the closest question on SO to my problem. Implementing the answer to this question did not help (I tried both [{display: false}] and [{display: true}]).
I am a novice at chartjs having only started working with it some ~5 days ago. Any help or advice would be appreciated.
Basically, I am writing a chart that takes data collected by a Raspberry Pi and plots it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Harp comfort</title>
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<h1>Temperature data</h1>
<canvas id="myChart"></canvas>
<script>
// Data from: Raspberry Pi Hat
window.addEventListener('load', setup);
var ops = {
scales: {
xAxes: [{
display: false
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
async function setup() {
const ctx = document.getElementById('myChart').getContext('2d');
const dataTemp = await getData();
const myChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [
{
label: 'Temperature',
data: dataTemp.temp,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.85)',
borderWidth: 2
}
]
},
options: ops
});
}
async function getData() {
const response = await fetch('./sample.csv');
const data = await response.text();
const temp = [];
const rows = data.split('\n').slice(1);
rows.forEach(row => {
const col = row.split(',');
temp.push(parseFloat(col[0]))
//console.log(col[0]) //for debugging purpose
});
return { temp };
}
//getData(); for debugging purpose
</script>
</body>
</html>
The CSV data (sample.csv) is available via this PasteBin page
I am answering my own question.
I was able to solve this problem by ensuring that the CSV data had 2 columns. A single column of data does not work. A two column data file (PasteBin Link) along with the modified code works fine:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Harp Temperature and RH</title>
<script src="https://cdn.jsdelivr.net/npm/jquery/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.8.0"></script>
</head>
<body>
<h1>Harp comfort</h1>
<canvas id="myChart" width="400" height="200"></canvas>
<script>
// Data from: Raspberry Pi Hat
window.addEventListener('load', setup);
var ops = {
scales: {
xAxes: [{
display: false
}],
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
};
async function setup() {
const ctx = document.getElementById('myChart').getContext('2d');
const dataTemp = await getData();
const myChart = new Chart(ctx, {
type: 'line',
data: {
labels: dataTemp.timestamp,
datasets: [
{
label: 'Temperature',
data: dataTemp.temp,
fill: false,
borderColor: 'rgba(255, 99, 132, 1)',
backgroundColor: 'rgba(255, 99, 132, 0.85)',
borderWidth: 2
}
]
},
options: ops
});
}
async function getData() {
const response = await fetch('./sample.csv');
const data = await response.text();
const timestamp = [];
const temp = [];
const rows = data.split('\n').slice(1);
rows.forEach(row => {
const col = row.split(',');
timestamp.push(col[0])
temp.push(parseFloat(col[1]))
//console.log(col[0]) //for debugging purpose
});
return { temp, timestamp };
}
//getData(); for debugging purpose
</script>
</body>
</html>
I would love it if more refined answers (than my novice solution!) be posted.

Cannot display two Chart.js on one HTML page

I am trying to display more Chart.js graphics on a single HTML page, but it does not work. I tried several approaches, but none of them had a positive result. I will attach my code:
#extends('layouts.app')
<!DOCTYPE html>
<html lang="zxx">
#section('content')
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/patternomaly#1.3.2/dist/patternomaly.min.js"></script>
#php
$dates = '';
$rates = '';
$graph_data = \App\Helpers\NjHelper::bettingData();
foreach ($graph_data as $item){
$dates .= "'".$item->date."',";
$rates .= $item->bankers.",";
}
#endphp
#php
$datesValue = '';
$ratesValue = '';
$graph_data_value = \App\Helpers\NjHelper::bettingDataValueBets();
foreach ($graph_data_value as $item){
$datesValue .= "'".$item->date."',";
$ratesValue .= $item->value_bet.",";
}
#endphp
<script>
$(function () {
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'line',
data: {
labels: [{!! $dates !!}],
datasets: [{
label: 'Bankers Profit Per Day',
data: [{!! $rates !!}],
borderColor: [
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
fontSize: 20
}
}
}
});
var ctx_2 = document.getElementById(chartValueBets).getContext('2d');
var chartValueBets = new Chart(ctx_2, {
type: 'line',
data: {
labels: [{!! $datesValue !!}],
datasets: [{
label: 'Value Bets Profit Per Day',
data: [{!! $ratesValue !!}],
borderColor: [
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)',
'rgba(243, 156, 18, 1)'
],
borderWidth: 3
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
labels: {
fontSize: 20
}
}
}
});
});
</script>
</head>
<div class="col-lg-12 col-xl-4">
<canvas id="myChart" width="400" height="400"></canvas>
<canvas id="chartValueBets" width="400" height="400"></canvas>
</div>
#endsection
</html>
The data that I want to be displayed comes from some SQL queries, this is the reason why I have those two #php sections before the charts.
Only the first chart appears on my HTML page, the one with the name "myChart".
Does anyone know what I could do in order to make the second one appear as well?
On the following line:
var ctx_2 = document.getElementById(chartValueBets).getContext('2d');
You are missing quotation marks around "chartValueBets." If you add quotation marks, it should work properly.

Categories