Multiple Charts in one page with Laravel & Chartjs - javascript

I'm trying to display two charts in one page. I'm expecting like 1 doughnut and 1 pie.
Here's my view snippets:
First Chart
<div class="card-body d-flex flex-center flex-column" style="width: 381px; height:350px;">
<!-- Find the JS file for the following chart at: src/js/charts/echarts/bandwidth-saved.js-->
<!-- If you are not using gulp based workflow, you can find the transpiled code at: public/assets/js/theme.js-->
<canvas id="pengeluaran" width="350"></canvas>
</div>
Second Chart
<div class="card-body d-flex flex-center flex-column" style="width: 381px; height:350px;">
<!-- Find the JS file for the following chart at: src/js/charts/echarts/bandwidth-saved.js-->
<!-- If you are not using gulp based workflow, you can find the transpiled code at: public/assets/js/theme.js-->
<canvas id="sponsorship" width="350"></canvas>
</div>
I tried the solution at Two charts in a page not working, using Chart.js 3.1.1 cdn in Laravel 8.x framework & Multiple charts in one page - Chartjs, but it's seems doesn't work for me. I tried to implement it, but only the first chart is displaying on the page.
It's displays the error "Failed to create chart: can't acquire context from the given item", I double check everything and I can't find what's cause of the error.
Here's the javascript file:
<script>
const ctx1 = document.getElementById('pengeluaran');
const ExpensesLabel = ['Rewards', 'Bantuan', 'Others'];
const ExpensesData = {
labels :ExpensesLabel,
datasets: [{
label: 'Sebaran Pengeluaran untuk Anak',
data: [300, 50, 100],
backgroundColor: [
"rgb(255, 99, 132, 0.2)", "rgb(54, 162, 235, 0.2)",
"rgb(255, 206, 86, 0.2)",
],
borderColor: [
"rgb(255, 99, 132, 1)", "rgb(54, 162, 235, 1)",
"rgb(255, 206, 86, 1)",
],
hoverOffset: 4,
borderWidth: 1,
}]};
const options1 = {
responsive: true,
maintainAspectRatio: true,
layout: {
padding: 10
}
};
new Chart(ctx1, {
type: 'doughnut',
data: ExpensesData,
options: options1
});
</script>
Second Charts
<script>
const ctx2 = document.getElementById('sponsorship');
const SponsorLabel = ['TK','SD','SMP','SMA-K / Kuliah'];
const SponsorData = {
labels : SponsorLabel,
datasets: [{
label: 'Sebaran Penerimaan Hadiah Sponsor',
data: [300, 50, 100, 90],
backgroundColor: [
"rgb(255, 99, 132, 0.2)", "rgb(54, 162, 235, 0.2)",
"rgb(255, 206, 86, 0.2)", "rgb(75, 192, 192, 0.2)",
],
borderColor: [
"rgb(255, 99, 132, 1)", "rgb(54, 162, 235, 1)",
"rgb(255, 206, 86, 1)", "rgb(75, 192, 192, 1)",
],
hoverOffset: 4,
borderWidth: 1
}]
};
const options2 = {
responsive: true,
maintainAspectRatio: true,
layout: {
padding: 10
}
};
new Chart(ctx2, {
type: 'pie',
data: SponsorData,
options: options2,
});
</script>
Is there anything I missed? Any help would be appreciated! Thanks

Sorry for late reply. The fix was it was conflicting id naming with other div in the blade file. So I had to rename the second chart canvas id to different name. The code above works perfectly though, as explained and tested by FiddlingAway in the comment section.
<canvas id="sponsorship-charts" width="350"></canvas>

Related

chart.js random weird problems

this to me makes absolutely no logical sense.
my graph.js was working until it randomly just stopped after passing local storage as a prop. i refactored to make the prop passed in completely unrelated to the local storage... which still shouldn't matter.
for some reason every single number i put into the data field works EXCEPT when i put in props.score/number or ANYTHING reassigned that number. ive never seen anything like it. when i console log number is is 82. it is a number (it is blue in the console) yet when i put it into chart.js it just won't appear.
what the heck is going on?!
this feels like typing 2+2 into a calculator and getting 5. i literally have no idea i have now been trying to figure this out for maybe 4 hours with absolutely no answer. once again...
this error just happened randomly today my app was working fine prior to this...?!
did chart.js change something as of yesterday?
is this a random bug ?
i have never run into such a problem after backtracking for so long. makes no sense.
import {useEffect} from 'react'
import Chart from 'chart.js';
import './BreakDown.css'
const LineChart = (props) => {
const number=props.score ***i am trying to get props.score into the chart js data point.
console.log(number) ****this console logs 82
const newNumber=10+number
console.log(newNumber) ***this console logs 92
useEffect(()=>{
var ctx = document.getElementById('myLineChart');
var myChart = new Chart(ctx, {
type: 'line',
responsive:true,
data: {
labels: ['X', 'IQ', 'X'],
datasets: [{
label: 'Your Score',
data: [0,newNumber,0], ***no matter what i do plug in in either of these numebnrs here doesn't work.
backgroundColor: [
'rgba(54, 80, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
],
borderWidth: 1,
},
{
label: 'Average',
data: [0, 100, 0],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
suggestedMin: 70,
suggestedMax: 160,
stepSize: 10
}
}]
}
}
});
},[])
return (
<div >
<canvas id="myLineChart" width="650" height="400"></canvas>
</div>
)
}
export default LineChart
to make things EVEN more bizarre if i plug in newNumber into the chart it gives me 10 in this case EVEN though console.logging newNumber gives me 92... HUH?!
Your code works fine on the first render for me. I am not 100% sure from your description what you think is going wrong, but 1 problem I see is that useEffect will only run once due to the [] in the second parameter.
If your prop.score updates, useEffect() won't run again, which means your chart won't update.
The main change I did below was add props.score in the array for useEffect, this tells useEffect to run again if props.score changes. You can read more about this in the useEffect docs
import React, { useEffect } from 'react'
import Chart from 'chart.js';
const LineChart = (props) => {
const number = props.score //***i am trying to get props.score into the chart js data point.
console.log(number) //****this console logs 82
const newNumber = 10 + number
console.log(newNumber) //***this console logs 92
useEffect(() => {
var ctx = document.getElementById('myLineChart');
var myChart = new Chart(ctx, {
type: 'line',
responsive: true,
data: {
labels: ['X', 'IQ', 'X'],
datasets: [{
label: 'Your Score',
data: [0, newNumber, 0],
backgroundColor: [
'rgba(54, 80, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(255, 99, 132, 1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
],
borderWidth: 1,
},
{
label: 'Average',
data: [0, 100, 0],
backgroundColor: [
'rgba(54, 162, 235, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(54, 80, 235, 0.2)',
],
borderColor: [
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
'rgba(255, 99, 132, .5)',
],
borderWidth: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: false,
suggestedMin: 70,
suggestedMax: 160,
stepSize: 10
}
}]
}
}
});
}, [props.score])
return (
<div >
<canvas id="myLineChart" width="650" height="400"></canvas>
</div>
)
}
export default LineChart

Graph made with chart js wont change size?

Im trying to learn a charting library in javascript and came across chart.js
Ive just copied the code from their installation front page as shown below.
My question is, why does changing the height and width parameters in the canvas element tag not actually change the size of the chart?
I believe this is explained on chart js's website "Detecting when the canvas size changes can not be done directly from the canvas element. Chart.js uses its parent container to update the canvas render and display sizes. However, this method requires the container to be relatively positioned and dedicated to the chart canvas only. Responsiveness can then be achieved by setting relative values for the container size (example):".
However I do not understand what container they are referring to as parent container as I cant find anything Ive specified in my code that could be referred to as parent container (pretty new to html, css and js).
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
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: 1
}]
},
options: {
scales: {
y: {
beginAtZero: true
}
}
}
});
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.3/dist/Chart.min.js"></script>
<canvas id="myChart" width="400" height="400"></canvas>
<script type="text/javascript" src="script.js"></script>
</body>
</html>
This issue you have here is that chartJS will ignore the width / height on the canvas element, so you need to wrap the canvas element in a div.....
<div style="width:400px;height:600px">
<canvas id="myChart"></canvas>
</div>

'require is not defined' error when attempting to use chartjs in javascript code

I'm neew to node and javascript. I am trying to incorporate chartjs into my project. I have a javascript file linked to an html file. The two files are shown below:
charts.html:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>Charts</title>
</head>
<body>
<p id="paragraph">This will be the Charts page.</p>
<canvas id="myChart" width="400" height="400"></canvas>
<script src="js/charts.js"></script>
</body>
</html>
charts.js:
//jshint esversion:6
var chart = require('chart.js'); //what's going on here??
var paragraph = document.querySelector("#paragraph");
//set click event listener
paragraph.addEventListener("click", changeMessage);
function changeMessage() {
paragraph.textContent = "clicked!";
console.log(paragraph.textContent);
}
var ctx = document.getElementById('myChart').getContext('2d');
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
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: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
}
}
});
The problem is in the way I'm importing the chart.js dependency. The line var chart = require('chart.js'); is what I am attempting, but when rendering the html page, I see a console error claiming: "Uncaught ReferenceError: require is not defined". Removing thatt line entirely makes the program complain about it not recognizing the Chart object.
Where am I going wrong here?
I recommend the cdnjs library imports. Just copy the link at the Chart.js-site and put it in your html-file.
<head>
<title>Charts</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.bundle.js">
</head>
If you are on node you need to npm install require.js. If you are not on node you can use ES6 Import.

Getting 'Chart is not defined' error when using chart.js in Meteor

I am using the official chart.js atmosphere package in my meteor application. I've tried running an example chart to see if I can pull it up however I am getting an issue saying "ReferenceError: Chart is not defined"
Here are the steps I took to installing the atmosphere package and running the code to produce the chart.
Installed the package with meteor add chart:chart
In my HTML I added the canvas tag calling the chart with it's informaiton
In the JS I added the function that creates the chart along with its relevant information
When I go to the page however, I just get an empty 400x400 image which is the canvas but there is no content there where the chart is supposed to be. Could someone assist me in figuring out what step I'm missing in order to get the chart to appear?
HTML
<template name="Home_page">
<canvas id="myChart" width="400" height="400"></canvas>
</template>
JS
import './home-page.html';
Template.Home_page.onRendered(function homePageOnRendered() {
var ctx = document.getElementById("myChart").getContext("2d");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
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: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
});
Ok I forgot to add
import Chart from 'chart.js'
in the top of my js file. That fixed it.

Is it possible to add a custom font to chart js?

I want to use a external font in my chart made with Chart JS. Does anyone know if that is possible? I've searched trough the documentation but I haven't found a solution.
It is indeed possible.
Considering you have imported your font (from GoogleFonts for instance),
you just have to edit the defaultFontFamily attribute in your chart options like this :
var options = {
// 'Raleway' is the name of the fond I imported from GoogleFonts
defaultFontFamily: Chart.defaults.global.defaultFontFamily = "'Raleway'"
}
See Lolka's answer for more information about the defaultFontFamily attribute.
A full working example:
Chart.defaults.global.defaultFontFamily = "Indie Flower";
var ctx = document.getElementById("myChart");
var myChart = new Chart(ctx, {
type: 'bar',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
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: 1
}]
},
options: {
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.1.6/Chart.min.js"></script>
<link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='stylesheet' type='text/css'>
<canvas id="myChart" width="400" height="400"></canvas>
First result for google Chart.JS custom font
From documentation:
There are 4 special global settings that can change all of the fonts
on the chart. These options are in Chart.defaults.global.
...
defaultFontFamily String "'Helvetica Neue', 'Helvetica', 'Arial',
sans-serif" Default font family for all text

Categories

Resources