I am trying to use the datasetFill option for the radar charts for chartjs and I noticed that the charts always stay filled even when I set datasetFill to false. Here is a link to a fiddle that gives an example of what I'm trying to do http://jsfiddle.net/5gHVY/143/. Here is the code below:
//line chart data
var lineData = {
labels: ["Jan", "Feb", "March", "April", "May", "June", "July"],
datasets: [{
fillColor: "rgba(255,255,0,100)",
strokeColor: "rgba(63,169,245,1)",
pointColor: "rgba(63,169,245,1)",
pointStrokeColor: "#fff",
data: [65, 59, 90, 81, 56, 55, 40]
}, {
fillColor: "rgba(255,255,255,0)",
strokeColor: "rgba(102,45,145,1)",
pointColor: "rgba(102,45,145,1)",
pointStrokeColor: "#fff",
data: [28, 48, 40, 19, 96, 27, 100]
}]
}
var lineOptions = {
animation: true,
pointDot: true,
scaleOverride : true,
scaleShowGridLines : false,
scaleShowLabels : true,
scaleSteps : 4,
scaleStepWidth : 25,
scaleStartValue : 25,
datasetFill: false,
};
var radarOptions = {
datasetFill: false,
};
//radar chart data
var radarData = {labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"],
datasets : [
{
fillColor: "rgba(102,45,145,.1)",
strokeColor: "rgba(102,45,145,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor: "rgba(63,169,245,.1)",
strokeColor: "rgba(63,169,245,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}
//Create Line chart
var ctx = document.getElementById("lineChart").getContext("2d");
var myNewChart = new Chart(ctx).Line(lineData, lineOptions);
//Create Radar chart
var ctx2 = document.getElementById("radarChart").getContext("2d");
var myNewChart2 = new Chart(ctx2).Radar(radarData, radarOptions);
edit: A pull request was just merged to fix this issue (https://github.com/nnnick/Chart.js/pull/1127), you will need to build the chart.js main file though as it is only in the src for the moment, just clone the project and run the gulp build.
The radar draw method is not taking this option into acount. Until a fix is present in the main Chart js you can extend the radar chart and override the draw method to take this option into account
Chart.types.Radar.extend({
// Passing in a name registers this chart in the Chart namespace in the same way
name: "RadarAlt",
draw : function(ease){
var easeDecimal = ease || 1,
ctx = this.chart.ctx;
this.clear();
this.scale.draw();
Chart.helpers.each(this.datasets,function(dataset){
//Transition each point first so that the line and point drawing isn't out of sync
Chart.helpers.each(dataset.points,function(point,index){
if (point.hasValue()){
point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
}
},this);
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
Chart.helpers.each(dataset.points,function(point,index){
if (index === 0){
ctx.moveTo(point.x,point.y);
}
else{
ctx.lineTo(point.x,point.y);
}
},this);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = dataset.fillColor;
if(this.options.datasetFill)
{
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
Chart.helpers.each(dataset.points,function(point){
if (point.hasValue()){
point.draw();
}
});
},this);
}
});
here it is in action
Chart.types.Radar.extend({
// Passing in a name registers this chart in the Chart namespace in the same way
name: "RadarAlt",
draw: function(ease) {
var easeDecimal = ease || 1,
ctx = this.chart.ctx;
this.clear();
this.scale.draw();
Chart.helpers.each(this.datasets, function(dataset) {
//Transition each point first so that the line and point drawing isn't out of sync
Chart.helpers.each(dataset.points, function(point, index) {
if (point.hasValue()) {
point.transition(this.scale.getPointPosition(index, this.scale.calculateCenterOffset(point.value)), easeDecimal);
}
}, this);
//Draw the line between all the points
ctx.lineWidth = this.options.datasetStrokeWidth;
ctx.strokeStyle = dataset.strokeColor;
ctx.beginPath();
Chart.helpers.each(dataset.points, function(point, index) {
if (index === 0) {
ctx.moveTo(point.x, point.y);
} else {
ctx.lineTo(point.x, point.y);
}
}, this);
ctx.closePath();
ctx.stroke();
ctx.fillStyle = dataset.fillColor;
if (this.options.datasetFill) {
ctx.fill();
}
//Now draw the points over the line
//A little inefficient double looping, but better than the line
//lagging behind the point positions
Chart.helpers.each(dataset.points, function(point) {
if (point.hasValue()) {
point.draw();
}
});
}, this);
}
});
var radarOptions = {
datasetFill: false,
};
//radar chart data
var radarData = {
labels: ["Eating", "Drinking", "Sleeping", "Designing", "Coding", "Partying", "Running"],
datasets: [{
fillColor: "rgba(102,45,145,.1)",
strokeColor: "rgba(102,45,145,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
data: [65, 59, 90, 81, 56, 55, 40]
}, {
fillColor: "rgba(63,169,245,.1)",
strokeColor: "rgba(63,169,245,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
data: [28, 48, 40, 19, 96, 27, 100]
}]
}
//Create Radar chart
var ctx2 = document.getElementById("radarChart").getContext("2d");
var myNewRadarChart = new Chart(ctx2).RadarAlt(radarData, radarOptions);
<script src="http://www.chartjs.org/assets/Chart.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="radarChart" width="800" height="650"></canvas>
Related
I already have an example of the cluster feature and I like the donut chart that is given out. This donut however is generated based on the clustering of data of lower levels.
What I'd like to do is generate a donut, pie or bar chart based on certain fields against certain co-ordinates.
For example, if I'm referring to satisfaction
Location Happy Neutral Sad Longitude Latitude
London 5 2 6 123123 -5432
And then generate a chart based upon the Happy Neutral Sad fields, at the given co-ordinates.
No donut chart, but I made a sample of a line chart using Chart.min.js. and jQuery. You surely can fill the gap using donut charts available in Chart.min.js
Here is a fiddle I have created to show you how to create a popup with a chart.
Relevant code is below.
First of all add your links to jquery and chart.js
<!-- jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<!-- ChartJS -->
<script src="https://cdn.jsdelivr.net/npm/chart.js#2.9.4/dist/Chart.min.js"></script>
Then you add a canvas that will be managed by chart.js
var popup = new mapboxgl.Popup({ closeOnClick: false })
.setLngLat([-96, 37.8])
.setHTML('<div class="chart"><canvas id="lineChart" style="min-height: 250px; height: 250px; max-height: 250px; max-width: 100%;"></canvas></div>')
.addTo(map);
and then add the data sources, options and render the chart in the canvas
//this is fake data just for testing
var areaChartData = {
labels : ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
datasets: [
{
label : 'Digital Goods',
backgroundColor : 'rgba(60,141,188,0.9)',
borderColor : 'rgba(60,141,188,0.8)',
pointRadius : false,
pointColor : '#3b8bba',
pointStrokeColor : 'rgba(60,141,188,1)',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(60,141,188,1)',
data : [28, 48, 40, 19, 86, 27, 90]
},
{
label : 'Electronics',
backgroundColor : 'rgba(210, 214, 222, 1)',
borderColor : 'rgba(210, 214, 222, 1)',
pointRadius : false,
pointColor : 'rgba(210, 214, 222, 1)',
pointStrokeColor : '#c1c7d1',
pointHighlightFill : '#fff',
pointHighlightStroke: 'rgba(220,220,220,1)',
data : [65, 59, 80, 81, 56, 55, 40]
},
]
}
//these are the options for testing
var areaChartOptions = {
maintainAspectRatio : false,
responsive : true,
legend: {
display: false
},
scales: {
xAxes: [{
gridLines : {
display : false,
}
}],
yAxes: [{
gridLines : {
display : false,
}
}]
}
}
var lineChartCanvas = $('#lineChart').get(0).getContext('2d')
var lineChartOptions = jQuery.extend(true, {}, areaChartOptions)
var lineChartData = jQuery.extend(true, {}, areaChartData)
lineChartData.datasets[0].fill = false;
lineChartData.datasets[1].fill = false;
lineChartOptions.datasetFill = false
var lineChart = new Chart(lineChartCanvas, {
type: 'line',
data: lineChartData,
options: lineChartOptions
})
I am having issues trying to get this chartJS piechart to render in PUG. I would like to put the chartJS code in its own folder and then render it across a PUG template. Can explain what I am doing wrong or point me to some docs that may hep with this? As everyone will be able to see I am attempting to try this in a few different ways. I have placed screen shots in hopes that someone might be able to tell me the cleanest way to go about it, as well as simply getting it to render on the page. I have placed screenshots, please let me know if there is any further info that I could provide. Thanks for any help you can provide.
[app.JS File][1]
const express = require('express');
const bodyParser = require('body-parser')
const path = require('path')
const app = express();
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname, 'css')));
app.set('view engine', 'pug')
app.locals.basedir = path.join(__dirname, 'views');
app.get ('/', (req, res) => {
res.render("dashboard", {title: "Home"})
})
app.listen(3000, () => {
console.log('listening to PORT 3000')
})
[JavaScript Pug Code][2]
$( document ).ready(function () {
var ctx = document.getElementById("myChart").getContext('2d');
var chart = new Chart(ctx, {
type: 'pie',
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
}
}]
}
}
});
})
[Main Dashboard Page][3]
html(lang="en")
head
meta(charset="UTF-8")
meta(name="viewport", content="width=device-width, initial-scale=1.0")
title USRA-NASA-NAMS
link(rel="stylesheet" href="./insight.css")
script(src="https://code.jquery.com/jquery-3.5.0.min.js")
script(src='https://cdn.jsdelivr.net/npm/chart.js#2.8.0')
script(type="text/javascript" src='pieChart.js')
<!DOCTYPE html>
<html>
<body>
<div id="chartContainer" style="height: 300px; width: 100%;">
<script type="text/javascript">
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer");
chart.options.axisY = { prefix: "$", suffix: "K" };
chart.options.title = { text: "Fruits sold in First & Second Quarter" };
var series1 = { //dataSeries - first quarter
type: "column",
name: "First Quarter",
showInLegend: true
};
var series2 = { //dataSeries - second quarter
type: "column",
name: "Second Quarter",
showInLegend: true
};
chart.options.data = [];
chart.options.data.push(series1);
chart.options.data.push(series2);
series1.dataPoints = [
{ label: "banana", y: 58 },
{ label: "orange", y: 69 },
{ label: "apple", y: 80 },
{ label: "mango", y: 74 },
{ label: "grape", y: 64 }
];
series2.dataPoints = [
{ label: "banana", y: 63 },
{ label: "orange", y: 73 },
{ label: "apple", y: 88 },
{ label: "mango", y: 77 },
{ label: "grape", y: 60 }
];
chart.render();
}
[Pug Page with PieChart Code][4]
div(class="chart")
canvas(id="chartPic" width="400" height="400")
script(src="chart.js")
script.
-window.onload = function() {
-var red="#{red}", green="#{green}", blue="#{blue}";
-var ctx = document.getElementById("chartPic").getContext('2d');
-var chart = new Chart(ctx, {
-type: 'pie',
-data: {
-labels: ["red", "green", "blue"],
-datasets: [{
-label: 'Number of votes',
-data: [1, 1, 1],
-backgroundColor: [red, green, blue],
-borderColor: [green, blue, red],
-borderWidth: 1
}],
},
-options: {
-title: {
-display: true,
-text: "chart",
},
-legend: {
-position: 'bottom'
},
}
});
};
I succesfully added second set of labels by following other question on SO.
But now I want to show legend for all labels and second set appears crossed out. How to avoid that?
Here is my attempt:
https://jsfiddle.net/L5gs39u2/1/
var platform_labels = ["Tablet","Ordenador"];
var platform_dataset = [14,5];
var os_labels = ["Android","Windows","GNU\/Linux"];
var os_dataset = [14,4,1];
var devices_labels = ["Tablet","Ordenador","Android","Windows","GNU\/Linux"];
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var config = {
type: 'doughnut',
data: {
datasets: [{
data: platform_dataset,
backgroundColor: [
chartColors.red,
chartColors.orange,
chartColors.yellow
],
label: 'Platform',
labels: platform_labels
}, {
data: os_dataset,
backgroundColor: [
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'OS',
labels: os_labels
}],
labels: devices_labels
},
options: {
tooltips: {
callbacks: {
label: function (tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
}
};
var ctx = document.getElementById('deviceChart').getContext('2d');
var employeesGraph = new Chart(ctx, config);
You have to generate the legend labels yourself by defining a legend.labels.generateLabels function together with a legend.onClick function that takes care of hiding and showing individual pie slices. This could look as follows:
legend: {
labels: {
generateLabels: () => {
let labels = [];
config.data.datasets.forEach((ds, iDs) => labels = labels.concat(ds.labels.map((l, iLabel) => ({
datasetIndex: iDs,
labelIndex: iLabel,
text: l,
fillStyle: ds.backgroundColor[iLabel],
hidden: employeesGraph ? employeesGraph.getDatasetMeta(iDs).data[iLabel].hidden : false,
strokeStyle: '#fff'
}))));
return labels;
}
},
onClick: (event, legendItem) => {
const metaData = employeesGraph.getDatasetMeta(legendItem.datasetIndex).data;
metaData[legendItem.labelIndex].hidden = !metaData[legendItem.labelIndex].hidden;
employeesGraph.update();
}
},
Please have a look at your amended code below:
var platform_labels = ["Tablet", "Ordenador"];
var platform_dataset = [14, 5];
var os_labels = ["Android", "Windows", "GNU\/Linux"];
var os_dataset = [14, 4, 1];
var devices_labels = ["Tablet", "Ordenador", "Android", "Windows", "GNU\/Linux"];
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var config = {
type: 'doughnut',
data: {
datasets: [{
data: platform_dataset,
backgroundColor: [
chartColors.red,
chartColors.orange,
],
label: 'Platform',
labels: platform_labels
}, {
data: os_dataset,
backgroundColor: [
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'OS',
labels: os_labels
}],
labels: devices_labels
},
options: {
legend: {
labels: {
generateLabels: () => {
let labels = [];
config.data.datasets.forEach((ds, iDs) => labels = labels.concat(ds.labels.map((l, iLabel) => ({
datasetIndex: iDs,
labelIndex: iLabel,
text: l,
fillStyle: ds.backgroundColor[iLabel],
hidden: employeesGraph ? employeesGraph.getDatasetMeta(iDs).data[iLabel].hidden : false,
strokeStyle: '#fff'
}))));
return labels;
}
},
onClick: (event, legendItem) => {
const metaData = employeesGraph.getDatasetMeta(legendItem.datasetIndex).data;
metaData[legendItem.labelIndex].hidden = !metaData[legendItem.labelIndex].hidden;
employeesGraph.update();
}
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var dataset = data.datasets[tooltipItem.datasetIndex];
var index = tooltipItem.index;
return dataset.labels[index] + ": " + dataset.data[index];
}
}
}
}
};
var ctx = document.getElementById('deviceChart').getContext('2d');
var employeesGraph = new Chart(ctx, config);
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.js"></script>
<canvas id="deviceChart" height="120"></canvas>
The second set of labels are striked through because chartjs see's them as hidden, i.e. they have no values so are not rendered and the labels are only getting drawn from the first dataset.
There is a few ways around this, you could either disable the legend and then create a custom legend but I'm not sure if this will grab all of the labels:
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
legend: {
display: false
},
legendCallback: function(chart) {
var text = [];
text.push('<ul>');
for (var i=0; i<devices_labels.length; i++) {
text.push('<li>');
text.push('<span style="background-color:' +
chart.data.datasets[i].borderColor + '">' + devices_labels[i] +
'</span>');
text.push('</li>');
}
text.push('</ul>');
return text.join("");
}
}
});
Or you could extend chartjs to change the behaviour of labels for hidden data:- change legend item style when dataset is hidden
Or the simplest way is to just add in some dummy data, to your first dataset:-
var platform_labels = ["Tablet","Ordenador"];
var platform_dataset = [14, 5, 0, 0, 0];
var os_labels = ["Android","Windows","GNU\/Linux"];
var os_dataset = [14,4,1];
var devices_labels = ["Tablet","Ordenador","Android","Windows","GNU\/Linux"];
var chartColors = {
red: 'rgb(255, 99, 132)',
orange: 'rgb(255, 159, 64)',
yellow: 'rgb(255, 205, 86)',
green: 'rgb(75, 192, 192)',
blue: 'rgb(54, 162, 235)',
purple: 'rgb(153, 102, 255)',
grey: 'rgb(201, 203, 207)'
};
var config = {
type: 'doughnut',
data: {
datasets: [{
data: platform_dataset,
backgroundColor: [
chartColors.red,
chartColors.orange,
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'Platform',
labels: platform_labels
}, {
data: os_dataset,
backgroundColor: [
chartColors.purple,
chartColors.green,
chartColors.blue
],
label: 'OS',
labels: os_labels
}],
labels: devices_labels
}
};
var ctx = document.getElementById('deviceChart').getContext('2d');
var employeesGraph = new Chart(ctx, config);
What I'd like to do, is to increase the margin between the y-axis values and the corresponding bar within the chart.
So if I have a bar in the chart which has a value of "Python" on the Y- axis, I want to increase the space between the string "Python" and the visual bar.
Now:
Python__========================================================
My goal:
Python___________=========================================================
___ represents the space between y-axis label and visual bar
I tried to use chartArea{right:200} and textPosition:out in the options section of the chart.
var options = {
chartArea:{right: 200},
'vAxis': {
title:'',
textStyle : {
fontSize: 25
},
textPosition: 'out'
},
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Coding-Skills', 'Skill-Level'],
['C', {v: 0.3, f:'low'}],
['Python', {v: 1, f:'medium'}],
['Javascript', {v: 1.5, f:'medium'}],
['HTML/CSS', {v: 1.5, f:'medium'} ]
]);
var options = {
chartArea: {
left: 1400
},
'hAxis': {
gridlines:{
count: 0},
textStyle : {
fontSize: 25
}
},
'vAxis': {
title:'',
textStyle : {
fontSize: 25
}
},
chart: {
},
bars: 'horizontal',
axes: {
x: {
0: { side: 'bottom', label: 'Years of experience'} ,
textStyle : {
fontSize: 35
}
}
}
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
Applying margin-right
no options for label margins,
but you can move them manually on the chart's 'ready' event
find the labels and change the 'x' attribute
see following working snippet,
here, the chartArea option is used to ensure there is enough room...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Language', 'Skill-Level'],
['C', 20],
['Python', 35],
['Javascript', 50]
]);
var container = document.getElementById('chart_div');
var chart = new google.visualization.BarChart(container);
google.visualization.events.addListener(chart, 'ready', function () {
var labels = container.getElementsByTagName('text');
Array.prototype.forEach.call(labels, function(label) {
// move axis labels
if (label.getAttribute('text-anchor') === 'end') {
var xCoord = parseFloat(label.getAttribute('x'));
label.setAttribute('x', xCoord - 20);
}
});
});
var options = {
chartArea: {
left: 100,
right: 200
},
colors: ['#aaaaaa'],
hAxis: {
baselineColor: 'transparent',
gridlines: {
count: 0
},
textStyle: {
color: '#aaaaaa'
}
},
height: 400,
legend: {
textStyle: {
color: '#aaaaaa'
}
},
vAxis: {
textStyle: {
color: '#aaaaaa'
}
}
};
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
Quick addition to existing answer:
$('.transactionValuationChart text').each(function(){
if( $(this).attr('text-anchor') == 'middle' ){
$(this).attr('y', parseFloat($(this).attr('y')) + 20 );
}else{
$(this).attr('x', parseFloat($(this).attr('x')) - 20 );
console.log("left");
}
});
This is a jQuery example which adds 20px of spacing to both x & y axis
My charts works well on the same page but when I put on different pages, only the first one works fine.
ex:
Page1.html
<div class="wrapper">
<canvas id="pieChart" width="200px" height="200px"></canvas>
</div>
Page2.html
<div class="wrapper">
<canvas id="lineChart" width="200px" height="200px"></canvas>
</div>
JS
//page1.html
//piechart
var pieVar = {
type: 'pie',
data: {
labels: ["Yes", "No"],
datasets: [
{
data: [60, 40],
backgroundColor: [
"#FF6384",
"#36A2EB"
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB"
]
}
]
},
options: {
scales: {
xAxes: [{
display: true
}]
}
}
}
//page2.html
//line chart
var lineVar = {
type: 'line',
data: {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: true,
lineTension: 0.2,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 10,
pointHoverBackgroundColor: "rgba(255,0,0,1)",
pointHoverBorderColor: "rgba(255,0,0,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
},
options: {
scales: {
xAxes: [{
display: true
}]
}
}
}
window.onload = function(){
//piechart
var pieCtx = document.getElementById("pieChart");
var myPieChart = new Chart(pieCtx, pieVar);
//linechart
var lineCtx = document.getElementById("lineChart");
var myLineChart = new Chart(lineCtx, lineVar);
};
In this codepen works fine because it's the same page..
CODEPEN
It sounds like you're loading the same JavaScript file (which contains the configurations for both of your charts) in both of your pages. The problem is since you're using a single JavaScript file with two chart definitions, the chart you try to create that doesn't exist in the html is throwing an error because you are passing in an empty context.
window.onload = function(){
//piechart (this will be null on page2.html)
var pieCtx = document.getElementById("pieChart");
// You are passing in a null pieCtx on page2.html because there is no element with an id = "pieChart"
var myPieChart = new Chart(pieCtx, pieVar);
//linechart (this will be null on page1.html)
var lineCtx = document.getElementById("lineChart");
// You are passing in a null lineCtx on page1.html because there is no element with an id = "lineChart"
var myLineChart = new Chart(lineCtx, lineVar);
};
You should either split your JavaScript file into two files so that the first page only includes the definition for the first chart and the second page only includes the definition for the second chart. Or, add some conditions to prevent trying to create the empty chart (like this).
window.onload = function(){
//piechart (this will be null on page2.html)
var pieCtx = document.getElementById("pieChart");
if (pieChart) {
var myPieChart = new Chart(pieCtx, pieVar);
}
//linechart (this will be null on page1.html)
var lineCtx = document.getElementById("lineChart");
if (lineChart) {
var myLineChart = new Chart(lineCtx, lineVar);
}
};