Chartjs.org Chart only displaying in one page - charts

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);
}
};

Related

Custom tooltip title based on dictionary mapping of values

MWE: See a graph below with countries in the x-axis. What is the best way to show the whole name in the tooltip instead of the acronym? (Show "Germany" instead of "GER", France instead of "FRA", etc.). I have like 10 or 15 of those.
SEE FULL CODE IN jsfiddle
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
https://jsfiddle.net/user3507584/6zpb715x/6/
You can add an object with translations where the key is the value from the label and the value is the full country name:
var example2 = [229, 113, 109];
var labels2 = ["GER", "FRA", "LT"];
var translations = {
GER: 'Germany',
FRA: 'France',
LT: "Italy"
}
var barChartData2 = {
labels: labels2,
datasets: [{
label: 'Student Count',
backgroundColor: '#ccece6',
data: example2
}]
};
function drawChart(el, data, title) {
var ctx = document.getElementById(el).getContext("2d");
var bar = new Chart(ctx, {
type: 'bar',
data: data,
options: {
// Elements options apply to all of the options unless overridden in a dataset
// In this case, we are setting the border of each bar to be 2px wide and green
elements: {
rectangle: {
borderWidth: 2,
borderColor: '#98c4f9',
borderSkipped: 'bottom'
}
},
responsive: true,
legend: {
position: 'bottom',
},
title: {
display: true,
text: title
},
scales: {
yAxes: [{
ticks: {
beginAtZero: 0,
min: 0
}
}],
xAxes: [{
ticks: {
// Show all labels
autoSkip: false,
callback: function(tick) {
var characterLimit = 20;
if (tick.length >= characterLimit) {
return tick.slice(0, tick.length).substring(0, characterLimit - 1).trim() + '...';;
}
return tick;
}
}
}]
},
tooltips: {
callbacks: {
title: function(tooltipItem) {
return translations[tooltipItem[0].xLabel];
}
}
}
}
});
console.log(bar);
};
drawChart('canvas0', barChartData2, 'example title');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.js"></script>
<div id="container">
<canvas id="canvas0"></canvas>
</div>

How can i give the full Legend a background color in chart js?

I am working on a project and we are using a chart created with chart js. I want to give the legend a background color (the top part thats drawn in the image). After a lot of searching on the internet i stil havent found a solution to my problem so i thought lets try stack overflow. can some one help me Please??>!
the part i want to give a background color
here is part of my code
enter code here
<div>
<canvas id="myChart"></canvas>
</div>
<script>
const labels = [
'January',
'February',
'March',
'April',
'May',
'June',
];
const data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: [0, 10, 5, 2, 20, 30, 45],
}]
};
const config = {
type: 'line',
data: data,
options: {}
};
var myChart = new Chart(
document.getElementById('myChart'),
config
);
</script>
You can use a custom plugin for this:
const plugin = {
id: 'legendBackground',
beforeDraw: (chart, args, opts) => {
const {
chartArea: {
width,
top,
left
},
ctx
} = chart;
ctx.fillStyle = opts.color || 'transparent';
ctx.fillRect(left, 0, width, top)
}
}
const options = {
type: 'line',
data: {
labels: ["Red", "Blue", "Yellow", "Green", "Purple", "Orange"],
datasets: [{
label: '# of Votes',
data: [12, 19, 3, 5, 2, 3],
borderColor: 'orange'
}]
},
options: {
plugins: {
legendBackground: {
color: 'pink'
}
}
},
plugins: [plugin]
}
const ctx = document.getElementById('chartJSContainer').getContext('2d');
new Chart(ctx, options);
<body>
<canvas id="chartJSContainer" width="600" height="400"></canvas>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.7.1/chart.js"></script>
</body>

Dual Axis Stacked Column Chart

I'm trying to create a dual axis stacked column Chart using Google's Classic Charts.
just like the Google's Material charts.
but there seems in classic one, the new stacks gets render over the previous one.
check the code below: Switch in between classic and material, you will find the difference.
Why classic? As it support tooltip modification unlike Material Chart.
Is it possible to have all stacks adjacent to the previous stack in classic chart?
google.charts.load('current', {
'packages': ['corechart', 'bar']
});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var button = document.getElementById('change-chart');
var chartDiv = document.getElementById('chart_div');
var data = google.visualization.arrayToDataTable([
['Galaxy', 'Distance', 'Brightness', 'Contrast', {
type: 'string',
role: 'tooltip',
'p': {
'html': true
}
}],
['Canis Major Dwarf', 8000, 23.3, 2.8, 'Irregular galaxy'],
['Sagittarius Dwarf', 24000, 3.5, 6.6, '5,000 ly'],
['Ursa Major II Dwarf', 30000, 14.3, 10.67, 'Half-light radius'],
['Lg. Magellanic Cloud', 50000, 0.9, 3.6, null],
['Bootes I', 60000, 13.1, 10.23, null]
]);
var materialOptions = {
width: 900,
isStacked: true,
chart: {
title: 'Nearby galaxies',
subtitle: 'distance on the left, brightness on the right'
},
series: {
0: {
axis: 'distance'
}, // Bind series 0 to an axis named 'distance'.
1: {
axis: 'brightness'
}, // Bind series 1 to an axis named 'brightness'.
2: {
axis: 'brightness'
} // Bind series 1 to an axis named 'brightness'.
},
axes: {
y: {
distance: {
label: 'parsecs'
}, // Left y-axis.
brightness: {
side: 'right',
label: 'apparent magnitude'
} // Right y-axis.
}
}
};
var classicOptions = {
width: 900,
isStacked: true,
series: {
0: {
targetAxisIndex: 0
},
1: {
targetAxisIndex: 1
},
2: {
targetAxisIndex: 1
}
},
title: 'Nearby galaxies - distance on the left, brightness on the right',
vAxes: {
// Adds titles to each axis.
0: {
title: 'parsecs'
},
1: {
title: 'apparent magnitude'
}
}
};
function drawMaterialChart() {
var materialChart = new google.charts.Bar(chartDiv);
materialChart.draw(data, google.charts.Bar.convertOptions(materialOptions));
button.innerText = 'Change to Classic';
button.onclick = drawClassicChart;
}
function drawClassicChart() {
var classicChart = new google.visualization.ColumnChart(chartDiv);
classicChart.draw(data, classicOptions);
button.innerText = 'Change to Material';
button.onclick = drawMaterialChart;
}
drawMaterialChart();
};
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<button id="change-chart">Change to Classic</button>
<br><br>
<div id="chart_div" style="width: 800px; height: 500px;"></div>
</body>
</html>

Google Charts: Data label with suffix

I am just starting with using google charts. I have a question. I would like to add data labels to my columns, in fact I have succeeded in this. However, I would like to add a suffix to these labels (percentages %). I have tried to use NumberFormat, but then no chart appears. What am I doing wrong?
<script type="text/javascript" src="https://www.google.com/jsapi"></script><script type="text/javascript">
google.load('visualization', '1', { 'packages': ['corechart'] } );
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Kenmerk', 'Belangrijkheid', { role: 'style' } ],
['Uitstellen', 10, 'color: gray'],
['bijwerkingen', 20, 'color: yellow'],
['behandelingen', 30, 'color: red'],
['Schema', 40, 'color: blue']
]);
var view = new google.visualization.DataView(data);
view.setColumns([0, 1,
{ calc: "stringify",
sourceColumn: 1,
type: "string",
role: "annotation" },
2]);
// Set chart options
var options = {
width: 800,
height: 600,
title: 'Uitslag',
vAxis: { title: 'belangrijkheid van elk kenmerk in percentages uitgedrukt', format: '#\'%\'', maxValue: '100', minValue: '0'},
legend: { position: 'none'},
bar: { groupWidth: '75%' },
};
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ColumnChart(document.getElementById("columnchart_values"));
chart.draw(view, options);
}
</script></p>
<div id="columnchart_values" style="width: 800px; height: 600px;">
</div>

Material design google charts change color column

When using Google charts, usually you can change the colors of individual columns by using the "role: style" function, but when I attempt it with the new material design charts I only get blue columns.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable([
['', '', { role: 'style' } ],
["Strongly disagree", 0, 'color: black'],
["Disagree", 0, 'color: #000000'],
["Neutral", 6, 'color: #212121'],
["Agree", 45, 'color: #212121'],
['Stongly agree', 98, 'color: black']
]);
var options = {
title: 'Instructor presented the subject matter clearly',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'General physics 221 CSUSB winter 2017' },
axes: {
},
bar: { groupWidth: "90%" }
};
var chart = new google.charts.Bar(document.getElementById('top_x_div'));
// Convert the Classic options to Material options.
chart.draw(data, google.charts.Bar.convertOptions(options));
};
You can try with netx code:
google.charts.load('current', {packages: ['corechart', 'bar']});
google.charts.setOnLoadCallback(drawColColors);
function drawColColors() {
var data = new google.visualization.arrayToDataTable([
['', '', { role: 'style' } ],
["Strongly disagree", 12, 'brown'],
["Disagree", 30, 'gray'],
["Neutral", 26, 'blue'],
["Agree", 45, 'color: #F05921'],
['Stongly agree', 58, 'black']
]);
var options = {
title: 'Instructor presented the subject matter clearly',
width: 900,
legend: { position: 'none' },
chart: { subtitle: 'General physics 221 CSUSB winter 2017' },
axes: {
},
bar: { groupWidth: "90%" }
};
//var chart = new google.charts.Bar(document.getElementById('chart_div'));
// Convert the Classic options to Material options.
//chart.draw(data, google.charts.Bar.convertOptions(options));
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>