Google Chart: "c.getTimezoneOffset is not a function" error - javascript

I'm trying to display a line chart of currency rates via google charts.
Basically i have 2 type of values:
Date (format iso8601)
Rate (decimal number)
When i try to render the chart with Date as type string, it renders nicely.
But when i try to render the chart with Date as type date/datetime, i get the following error:
"c.getTimezoneOffset is not a function"
Here is my code:
PHP array making:
$arrayForChart =array();
foreach ($arrayRates as $key => $value) {
$dateObj= new datetime($value['date']);//$value['date']= date in iso 8601 format: e.g 2017-02-12
$dateStringNewDate="new Date(" . $dateObj->format('Y') .",". $dateObj->format('m') . "," . $dateObj->format('d') . ")";//temp for testing
$dateStringDate="Date(". $value['date'] . ")";//temp for testing
array_unshift($arrayForChart, array($dateStringDate , $value['rates']["$toCurrency"]));
}
array_unshift($arrayForChart, array(array('label'=>'Date','id'=>'Date','type'=>'date'),array('label'=>'Rate','id'=>'Rate','type'=>'number')));
Javascript
function dipsplayChart() {
//from here google chart stuff
google.charts.load("current", { packages: ["corechart", "line"] });
google.charts.setOnLoadCallback(drawLineColors);
function drawLineColors() {
console.log(JSON.stringify(arrayForChart));
var data = google.visualization.arrayToDataTable(arrayForChart);
var options = {
title: baseCurrency + " vs " + toCurrency + " Last 90 days",
explorer: {
actions: ["dragToZoom", "rightClickToReset"],
axis: "horizontal",
keepInBounds: true
},
hAxis: {
title: "Date"
//type: "date"
},
vAxis: {
title: "Rate"
//type: "number"
},
colors: ["#a52714", "#097138"]
};
var chart = new google.visualization.LineChart(
document.getElementById("chart_div")
);
chart.draw(data, options);
}
//until here google chart stuff
}
Data example:
[[{"label":"Date","id":"Date","type":"date"},{"label":"Rate","id":"Rate","type":"number"}],["new Date(2017,04,10)",3.6618],["new Date(2017,04,11)",3.6565],["new Date(2017,04,12)",3.6551],["new Date(2017,04,13)",3.6539],["new Date(2017,04,18)",3.6652],["new Date(2017,04,19)",3.6655],["new Date(2017,04,20)",3.6651],["new Date(2017,04,21)",3.6798],["new Date(2017,04,24)",3.6523],["new Date(2017,04,25)",3.6443],["new Date(2017,04,26)",3.6365],["new Date(2017,04,27)",3.644],["new Date(2017,04,28)",3.622],["new Date(2017,05,02)",3.6094],["new Date(2017,05,03)",3.6171],["new Date(2017,05,04)",3.6191],["new Date(2017,05,05)",3.6038],["new Date(2017,05,08)",3.6049],["new Date(2017,05,09)",3.6034],["new Date(2017,05,10)",3.6007],["new Date(2017,05,11)",3.6114],["new Date(2017,05,12)",3.6045],["new Date(2017,05,15)",3.597],["new Date(2017,05,16)",3.6056],["new Date(2017,05,17)",3.6017],["new Date(2017,05,18)",3.6045],["new Date(2017,05,19)",3.5859],["new Date(2017,05,22)",3.5817],["new Date(2017,05,23)",3.5871],["new Date(2017,05,24)",3.5897],["new Date(2017,05,25)",3.5769],["new Date(2017,05,26)",3.5734],["new Date(2017,05,29)",3.5724],["new Date(2017,05,30)",3.5517],["new Date(2017,05,31)",3.5431],["new Date(2017,06,01)",3.5511],["new Date(2017,06,02)",3.5605],["new Date(2017,06,05)",3.549],["new Date(2017,06,06)",3.5461],["new Date(2017,06,07)",3.5457],["new Date(2017,06,08)",3.5358],["new Date(2017,06,09)",3.5242],["new Date(2017,06,12)",3.533],["new Date(2017,06,13)",3.5258],["new Date(2017,06,14)",3.5295],["new Date(2017,06,15)",3.5225],["new Date(2017,06,16)",3.5274],["new Date(2017,06,19)",3.5225],["new Date(2017,06,20)",3.5391],["new Date(2017,06,21)",3.5409],["new Date(2017,06,22)",3.5441],["new Date(2017,06,23)",3.5418],["new Date(2017,06,26)",3.531],["new Date(2017,06,27)",3.5168],["new Date(2017,06,28)",3.52],["new Date(2017,06,29)",3.4955],["new Date(2017,06,30)",3.4953],["new Date(2017,07,03)",3.4979],["new Date(2017,07,04)",3.516],["new Date(2017,07,05)",3.5195],["new Date(2017,07,06)",3.5361]]
Anybody know what is the problem?
Many thanks!!

Related

How to add a second series in highcharts [duplicate]

This question already has an answer here:
Retrieving JSON data for Highcharts with multiple series?
(1 answer)
Closed 2 years ago.
I have been trying to display the second value of my json file in highcharts for two days.
my json file:
[[1591518187000,17.3,12.7],[1591518135000,17.2,12.7]...[1591518074000,17.2,12.6],[1591518020000,17.2,12.7]]
The time and the first value are displayed correctly.
my script in php file:
<script type="text/javascript">
var chart;
function requestData() {
$.getJSON('../****json.php',
function (data) {
var series = chart.series[0];
series.setData(data);
}
);
}
(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
defaultSeriesType: 'line',
marginRight: 10,
marginBottom: 25,
events: { load: requestData }
},
.....
series: [{
name: 'Temperatur',
data: []
},
{
name: "Taupunkt",
data: []
......
</script>
Does anyone happen to have a way of drawing the second values ​​as a line?
You could process your data and make two data sets for both series. Both data sets will have the same x values, but different y values. The code could look something like this:
$.getJSON('../****json.php',
function (data) {
var dataSetOne = [],
dataSetTwo = [];
data.forEach(function(point) {
dataSetOne.push([point[0], point[1]);
dataSetTwo.push([point[0], point[2]);
});
chart.series[0].setData(dataSetOne);
chart.series[1].setData(dataSetTwo);
}
);

Uncaught (in promise) Error: Row 1 has 42 columns, but must have 2

I'm using google bar charts for my project and I create an ajax function to load charts with data. But when I use jquery each function to create data bars in google charts its getting error called
Uncaught (in promise) Error: Row 1 has 42 columns, but must have 2. Can Anyone show me the error in my code
This is my chart code
//chart 2
google.charts.load('current', {
'packages': ['bar']
});
google.charts.setOnLoadCallback(drawChart1);
function drawChart1() {
var dataa1 = google.visualization.arrayToDataTable([
['DS Division', 'No of Youths'],
$.each(data.locations, function(index, value3) {
['' + value3.DSD_Name + '', value3.total]
}),
]);
var options1 = {
chart: {
},
bars: 'horizontal', // Required for Material Bar Charts.
legend: {
position: 'none'
},
};
var chart1 = new google.charts.Bar(document.getElementById('barchart_material'));
chart1.draw(dataa1, google.charts.Bar.convertOptions(options1));
}
This is my response data from the controller
return response() => json(array(
'male' => $male,
'female' => $female,
'locations' => $locations,
'salary1' => $salary1,
'salary2' => $salary2,
'salary3' => $salary3,
'salary4' => $salary4,
'salary5' => $salary5,
'salary6' => $salary6,
'employers' => $employers
));
Please help me to slove this
Thank You
instead of trying to loop within the array declaration,
use the loop to add values to the array...
var chartData = [
['DS Division', 'No of Youths'],
];
$.each(data.locations, function(index, value3) {
chartData.push([value3.DSD_Name, value3.total]);
});
var dataa1 = google.visualization.arrayToDataTable(chartData);

Update title dynamically on Apexcharts

I am using Updateseries to update x and y axis. How can i update title?
$.getJSON('chartData.php', {
devicename: feature.get('id')
}, (response) => {
chart.updateSeries([{
data: response
}])
let chart = new ApexCharts(document.getElementById("chart"), options)
chart.updateOptions({
title: 'Water Consumption per day on December 2019 for '
})
});
You should use the updateOptions method of ApexCharts to update any other configuration.
updateSeries only deals with data of the chart, while updateOptions allows changing the configuration of the chart dynamically
var chart = new ApexCharts(el, options);
chart.updateOptions({
title: {
text: 'new title'
}
})
Docs for updateOptions - https://apexcharts.com/docs/methods/#updateOptions
this code can update the title in the chart.
*ApexCharts.exec('id', "updateOptions", {*
title:{
text:title1
}
});

Trouble showing results with pie highchart

I'm totally new to Highcharts and I made two types of them: spline and pie. They now look like this:
And this:
The problem I have can be seen immediately. Since I have two buttons on which user can determine how he wants his chart to appear:
I succeed to update chart type like so:
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
});
}
});
But I don't want this pie chart to appear like this. I want, like in spline type that values represent each day, not Notiflow:35 etc. This is code responsible for charts:
var type='';
$('#spline').click(function(){
if($('#spline').hasClass('active')!=true){
$('#pie').removeClass('active');
$('#spline').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "spline"
});
}
});
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
});
}
});
$(function () {
if($('#spline').hasClass('active')){
type='spline';
}else{
type='pie';
}
$('#curve_chart').highcharts({
chart: {
type: type
},
title: {
text: 'Click through rate:'
},
xAxis: {
categories: [<?php foreach ($percentagePerDay as $key => $value) {
if ($value != $last) {
echo substr($key, -2);
echo ',';
} else {
echo substr($key, -2);
}
}?>]//key
},
yAxis: {
title: {
text: 'Percentage'
}
},
series: [{
name: '<?= $name ?>',
data: [<?php foreach ($percentagePerDay as $key => $value) {
if ($value != $last) {
echo $value;
echo ',';
} else {
echo $value;
}
}?>]//value
}]
});
});
I tried to make pie chart to represent hard coded values like so:
$('#pie').click(function(){
if($('#pie').hasClass('active')!=true){
$('#spline').removeClass('active');
$('#pie').addClass('active');
$('#curve_chart').highcharts().series[0].update({
type: "pie"
series:[{
data:[['11',35],['12',15],['13',30],['14',20]]
}]
});
}
});
}
});
But pie highchart didn't changed. What more do I need to add to this line(except of type):
$('#curve_chart').highcharts().series[0].update({});
in order for my pie to represent values for each day within range like spline does and to remove those 'slice' moments?
UPDATE:
So, this is how I want my pie to look:
When updating series o not pass series in object - only series properties, like name, type, data, etc. To have dataLabels like in the image you only will need to set names for points, Highcharts will make it work.
Example: http://jsfiddle.net/tvd6faf9/

JavaScript Chart.js - Custom data formatting to display on tooltip

I have looked at various documentation and similar questions on here, but cannot seem to find the particular solution. Apologies if I have missed anything obvious or have repeated this question!
As a bit of background info, I have implemented 4 graphs using the Chart.js plugin and passed in the required data using PHP from a database. This is all working correctly and is fine.
My problem is I need to display the data in the tooltips as formatted data aka. as numeric with %. As an example, one of my data from database is -0.17222. I have formatted it as a percentage to display in my table and all is well. However, when setting the data for the chart.js bar graph, the data is obviously missing this formatting and displaying as the -0.17222 which I do not want.
Sorry, I wanted to post a picture, but my reputation is too rubbish!
I grab data from database, then set into my table:
var kpiRex = new Handsontable(example1, {
data: getRexData(),
Then I feed this data like so in the chart section:
data: kpiRex.getDataAtRow(3)
Any help would be great! I've been stuck on this for hours and it's probably something really simple I am overlooking.
For chart.js 2.0+, this has changed (no more tooltipTemplate/multiTooltipTemplate). For those that just want to access the current, unformatted value and start tweaking it, the default tooltip is the same as:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return tooltipItem.yLabel;
}
}
}
}
I.e., you can return modifications to tooltipItem.yLabel, which holds the y-axis value. In my case, I wanted to add a dollar sign, rounding, and thousands commas for a financial chart, so I used:
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
return "$" + Number(tooltipItem.yLabel).toFixed(0).replace(/./g, function(c, i, a) {
return i > 0 && c !== "." && (a.length - i) % 3 === 0 ? "," + c : c;
});
}
}
}
}
You want to specify a custom tooltip template in your chart options, like this :
// String - Template string for single tooltips
tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
// String - Template string for multiple tooltips
multiTooltipTemplate: "<%= value + ' %' %>",
This way you can add a '%' sign after your values if that's what you want.
Here's a jsfiddle to illustrate this.
Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.
This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.
Note that Your datasets should only contain numeric values. (No % signs or other stuff there).
In chart.js 2.1.6, I did something like this (in typescript):
let that = this;
options = {
legend: {
display: false,
responsive: false
},
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let account: Account = that.accounts[tooltipItem.index];
return account.accountNumber+":"+account.balance+"€";
}
}
}
}
You can give tooltipTemplate a function, and format the tooltip as you wish:
tooltipTemplate: function(v) {return someFunction(v.value);}
multiTooltipTemplate: function(v) {return someOtherFunction(v.value);}
Those given 'v' arguments contain lots of information besides the 'value' property. You can put a 'debugger' inside that function and inspect those yourself.
tooltips: {
callbacks: {
label: (tooltipItem, data) => {
// data for manipulation
return data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
},
},
},
This works perfectly fine with me. It takes label and format the value.
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
let label = data.labels[tooltipItem.index];
let value = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index];
return ' ' + label + ': ' + value + ' %';
}
}
}
}
tooltips: {
callbacks: {
label: function (tooltipItem) {
return (new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})).format(tooltipItem.value);
}
}
}
In Chart.Js 2.8.0, the configuration for custom tooltips can be found here: https://www.chartjs.org/docs/latest/configuration/tooltip.html#label-callback (Thanks to #prokaktus)
If you want to e.g. show some values with a prefix or postfix (In the example, the script adds a unit of kWh to the values in the chart), you could do this like:
options: {
rotation: 1 * Math.PI,
circumference: 1 * Math.PI,
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
console.log(data);
console.log(tooltipItem);
var label = data.datasets[tooltipItem.datasetIndex].data[tooltipItem.index] || '';
if (label) {
label += ' kWh';
}
return label;
}
}
}
}
An example fiddle is here, too: https://jsfiddle.net/y3petw58/1/
This is what my final options section looks like for chart.js version 2.8.0.
options: {
legend: {
display: false //Have this or else legend will display as undefined
},
scales: {
//This will show money for y-axis labels with format of $xx.xx
yAxes: [{
ticks: {
beginAtZero: true,
callback: function(value) {
return (new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})).format(value);
}
}
}]
},
//This will show money in tooltip with format of $xx.xx
tooltips: {
callbacks: {
label: function (tooltipItem) {
return (new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
})).format(tooltipItem.value);
}
}
}
}
I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)
The answers here did not work for me on Char.js 3.8.0. The tooltip options callbacks object has moved, apparently. Now it is under options.plugins.tooltip
https://www.chartjs.org/docs/latest/configuration/tooltip.html
Example for OP:
options: {
plugins: {
tooltip: {
callbacks: {
label: function (tooltipItem, data) {
console.log(data);
console.log(tooltipItem);
return tooltipItem.formattedValue + '%';
}
}
}
},
...
tooltips: {
enabled: true,
mode: 'single',
callbacks: {
label: function(tooltipItems, data) {
return data.datasets[tooltipItems.datasetIndex].label+": "+tooltipItems.yLabel;
}
}
}
You need to make use of Label Callback.
A common example to round data values, the following example rounds the data to two decimal places.
var chart = new Chart(ctx, {
type: 'line',
data: data,
options: {
tooltips: {
callbacks: {
label: function(tooltipItem, data) {
var label = data.datasets[tooltipItem.datasetIndex].label || '';
if (label) {
label += ': ';
}
label += Math.round(tooltipItem.yLabel * 100) / 100;
return label;
}
}
}
}
});
Now let me write the scenario where I used the label callback functionality.
Let's start with logging the arguments of Label Callback function, you will see structure similar to this here datasets, array comprises of different lines you want to plot in the chart.
In my case it's 4, that's why length of datasets array is 4.
In my case, I had to perform some calculations on each dataset and have to identify the correct line, every-time I hover upon a line in a chart.
To differentiate different lines and manipulate the data of hovered tooltip based on the data of other lines I had to write this logic.
callbacks: {
label: function (tooltipItem, data) {
console.log('data', data);
console.log('tooltipItem', tooltipItem);
let updatedToolTip: number;
if (tooltipItem.datasetIndex == 0) {
updatedToolTip = tooltipItem.yLabel;
}
if (tooltipItem.datasetIndex == 1) {
updatedToolTip = tooltipItem.yLabel - data.datasets[0].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 2) {
updatedToolTip = tooltipItem.yLabel - data.datasets[1].data[tooltipItem.index];
}
if (tooltipItem.datasetIndex == 3) {
updatedToolTip = tooltipItem.yLabel - data.datasets[2].data[tooltipItem.index]
}
return updatedToolTip;
}
}
Above mentioned scenario will come handy, when you have to plot different lines in line-chart and manipulate tooltip of the hovered point of a line, based on the data of other point belonging to different line in the chart at the same index.

Categories