Google column chart showing incorrect date - html

I am working on google column chart. I have created 3 columns while generating charts. Here are those columns.
var dtblData = new google.visualization.DataTable();
dtblData.addColumn('string', 'Names');
dtblData.addColumn('datetime', 'Intime');
dtblData.addColumn('datetime', 'Outtime');
I am using following data to show on graph.
[{"display_name":"Aditi Badurkar
","in_time":{"year":2017,"month":6,"day":22,"hours":11,"minutes":7,"seconds":8,"miliseconds":470},"out_time":{"year":2017,"month":6,"day":22,"hours":12,"minutes":45,"seconds":44,"miliseconds":237}}]
Here is my code :-
google.charts.load('current', { 'packages': ['corechart', 'bar'] });
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var chartDiv = document.getElementById('chart_div');
var dtblData = new google.visualization.DataTable();
dtblData.addColumn('string', 'Names');
dtblData.addColumn('datetime', 'Intime');
dtblData.addColumn('datetime', 'Outtime');
for (var i = 0; i < data.length; i++) {
if (data[i].out_time.year == 0) {
dtblData.addRow([data[i].display_name, new Date(data[i].in_time.year, data[i].in_time.month, data[i].in_time.day, data[i].in_time.hours, data[i].in_time.minutes, data[i].in_time.seconds, data[i].in_time.miliseconds), null]);
}
else {
dtblData.addRow([data[i].display_name, new Date(data[i].in_time.year, data[i].in_time.month, data[i].in_time.day, data[i].in_time.hours, data[i].in_time.minutes, data[i].in_time.seconds, data[i].in_time.miliseconds), new Date(data[i].out_time.year, data[i].out_time.month, data[i].out_time.day, data[i].out_time.hours, data[i].out_time.minutes, data[i].out_time.seconds, data[i].out_time.miliseconds)]);
}
}
var dateinFormat = new google.visualization.DateFormat({ formatType: 'long', pattern: "dd/MM/yyyy HH:mm:ss ZZZZ" });
dateinFormat.format(dtblData, 1);
var dateOutFormat = new google.visualization.DateFormat({ formatType: 'long', pattern: "dd/MM/yyyy HH:mm:ss ZZZZ" });
dateOutFormat.format(dtblData, 2);
var materialOptions = {
//width: 900,
chart: {
title: '',
subtitle: 'Intime, Outime of your kids or staff'
},
series: {
0: { axis: 'In Time' }, // Bind series 0 to an axis named 'In Time'.
1: { axis: 'Out time' } // Bind series 1 to an axis named 'Out Time'.
},
axes: {
y: {
distance: { label: 'In Time' }, // Left y-axis.
brightness: { side: 'right', label: 'Out Time' }, // Right y-axis.
}
},
};
function drawMaterialChart() {
var materialChart = new google.charts.Bar(chartDiv);
materialChart.draw(dtblData, google.charts.Bar.convertOptions(materialOptions));
}
drawMaterialChart();
}
My problem is, on graph it is showing month as July but in data it is June. I am not getting why it is showing wrong month when I scroll mouse pointer on bar? Can someone help me to solve this? I think it might be time zone issue.
Please see screenshot.

The Month in JavaScript is Zero Based, so ranges from 0 to 11 (0 meaning January and 11 meaning December).
For your code, you may decrement the month value by 1 to solve this.
Something that may be useful:
Why does the month argument range from 0 to 11 in JavaScript's Date constructor?

Related

node js mysql query result rendered to chart.js labels in pug page

I've this strange behaviour when i make a get request. A query to mysql calls for totals of sells(float) group by days (nvarchar). I've made 2 arrays (for totals and datas) where i push the content of the result
router.get('/movmensili', function(req, res ,next){
if(!req.session.user){
return res.redirect('/');
}
executeQuery("SELECT SUM(price) as Totale, Data FROM db10101.10101 group by Data order
by Data", function(error, resmov){
var dateArray = [];
var totaliArray = [] ;
for (var i = 0; i<resmov.length; i++) {
dateArray.push(resmov[i].Data)
}
for (var i = 0; i<resmov.length; i++) {
totaliArray.push(resmov[i].Totale)
}
res.render('movmensili', {title: 'movs', date: (dateArray), totali: totaliArray
});
});
});
console.log(dateArray); //['2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05']
console.log(totaliArray); //[ '4.00', '5.50', '3.00', '1.75', null ]
so far so good
once I open my Pug page i got to draw a bar chart with Chart.js
the two arrays used for the chart axes, contains numeric values, no problems for the sell totals, but the xlabels should be strings. So far the xlabes are 2016(=2022 minus 05 minus 01), 2015, 2014 and so on....
canvas#myChart(style='width: 100%; height: 100%; margin: 10 auto')
script.
const xlabels = [#{date}] //[2022-05-01,2022-05-02,2022-05-03,2022-05-04,2022-05-05]
const ydatas = [#{totali}] //[4.00,5.50,3.00,1.75,]
I wasn't able to convert / cast / stringify the x values to get the result needed.
Any suggestions?
David, this worked for me. Are you sure you are passing the labels correctly on render (try date: dateArray instead of date: (dateArray)). I didn't create a render function for this page so hard coded the labels and data arrays:
script.
var labels = ['2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05',]
var data = {
labels: labels,
datasets: [{
label: 'My First dataset',
backgroundColor: 'rgb(255, 99, 132)',
borderColor: 'rgb(255, 99, 132)',
data: ['4.00', '5.50', '3.00', '1.75', null],
}]
};
var config = {type: 'line',data: data,options: {}};
var myChart = new Chart(document.getElementById("myChart"),config);
Not best solution, but it works....
async function GetData()
var xlabel = '#{date}';
var xlabel = xlabel.replace(/"/g, '"');
alert(xlabel);
var xlabel = xlabel.split(",");
alert(xlabel);
for(i = 0; i < xlabel.length; i += 1){
xlabel[i] = xlabel[i];
//alert(numarray[i]);
xlabels.push(xlabel[i]);
}
if I hardcode the labels in:
const xlabels = [#{date}]
instead of importing from page render, everything works fine. It's exactly that the point. The console.log of dateArray is perfectly as I would like to be in the xlabels, while once imported the quotes disappear
console.log(dateArray); // ['2022-05-01','2022-05-02','2022-05-03','2022-05-04','2022-05-05']
const xlabels = [#{date}]; // [2022-05-01,2022-05-02,2022-05-03,2022-05-04,2022-05-05]

Chart.js time series

Just to preface, I'm very new to code! I'm working with Chart.js to show the number of recruitment candidates generated from a marketing campaign. I'm trying to display the data generated on a weekly basis. So I'll have a start date and the x-axis will show every next week. Right now, I can only get it to show every day. Again, I'm not well versed on the topic just yet so I apologize if I'm not explaining it properly. For this example the x-axis would sat 2020/11/20, 2020/12/07, 2020/12/14 and so on. Thanks!
What I have so far
<script src='https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js'></script>
<canvas id="timeSeriesChart"></canvas>
<script>
Chart.defaults.global.defaultFontFamily = 'Poppins';
const ctx = document.getElementById('timeSeriesChart').getContext('2d');
const startDate = new Date(2020, 10, 30);
const labels = [];
for (let i = 0; i < 13; i++) {
const date = moment(startDate).add(i, 'days').format('YYYY/MM/DD');
labels.push(date.toString());
}
const chart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Recruitment Candidates',
data: [4, 5, 6, 90, 56, 32, 14, 6, 72, 99],
borderWidth: 1
}]
},
options: {}
});
</script>
Welcome to the world of coding. Never mind asking questions - it's professional, and we all started one day :-)
I hope I understood correctly your need and offer a solution right away with latest version:
Chart.js v3.xx (not compatible with v2.xx)
Time Series Axis (with moment.js + adapter):
Source: https://www.chartjs.org/docs/latest/axes/cartesian/timeseries.html
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
//gets you the latest version of chart, now v3.2.1
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chartjs-adapter-moment"></script>
//you need this adapter for timeseries to work with momentjs
<div>
<canvas id="timeSeriesChart"></canvas>
</div>
<script>
Chart.defaults.font.family = 'Poppins';
// watch out, it's not Chart.defaults.global.defaultFontFamily anymore as in v2.xx
const ctx = document.getElementById('timeSeriesChart').getContext('2d');
const startDate = new Date(2020, 10, 30);
const labels = [];
let i = 0;
//tip: declare variable `i` outside `for ()` loop - better performance
let date = new Date();
//also: declare variable `date` outside `for ()` loop
for (i; i < 13; i++) {
date = moment(startDate).add(i, 'weeks').format('YYYY/MM/DD');
//add `weeks` instead of `days` if you have weekly totals
//add `days` if you have daily totals
labels.push(date.toString());
}
const chart = new Chart(ctx, {
type: 'line',
data: {
labels,
datasets: [{
label: 'Recruitment Candidates',
data: [4, 5, 6, 90, 56, 32, 14, 6, 72, 99],
borderWidth: 1,
tension: 0.3,
fill: true
}]
},
options: {
scales: { //watch out here - new syntax in v3.xx
x: {
type: 'timeseries',
time: {
unit: 'week', //this does the trick :-)
isoWeekday: true,
// declare Monday as the first day of the week
// because in some locale, sunday would be first day of week
}
}
}
}
});
</script>
You should get following result:
Hope this helps and happy coding ...

How to get data event click in angular google chart-angular 2+

I used the google charts in my angular project dashboard.
By reading the document: https://github.com/FERNman/angular-google-charts , I used the below code for getting the event(which should contain the elements of the chart which I selected)
As per the document, the select event is emitted when an element in the chart gets selected.
<google-chart (select)="onSelect($event)"></google-chart>
I used the same in my code.
Html:`
<google-chart #chart [title]="Bartitle" [type]="Bartype" [data]="Bardata" [columnNames]="BarcolumnNames"
[options]="Baroptions" [width]="Barwidth" [height]="Barheight"
(select)="onSelect($event)">
</google-chart>`
Component.Ts
this.Bartitle = 'Current and Target';
this.Bartype = 'BarChart';
this.Bardata = [
["2012", 900, 390],
["2013", 1000, 400],
["2014", 1170, 440],
["2015", 1250, 480],
["2016", 1530, 540]
];
this.BarcolumnNames = ["Year", "Current", "Target"];
this.Baroptions = {
hAxis: {
title: 'Maturity'
},
vAxis: {
title: 'Month'
},
};
this.Barwidth = 200;
this.Barheight = 200;
onSelect(event) {
console.log(event);
}
But I dont get the values which I selected..
I need the values of maturity and the year... How i get that?? Did I made any changes??
Select
The select event is emitted when an element in the chart gets selected.
<google-chart (select)="onSelect($event)"></google-chart>
The event of type ChartSelectionChangedEvent containing an array of selected values.
in component
EDIT : Based on comments
onSelect(event) {
const { row, column } = event[0];
const year = this.Bardata[row][0];
let selectedItem;
if (column === 1) {
selectedItem = "current";
}
if (column === 2) {
selectedItem = "target";
}
console.log("year", year, "SelectedItem" ,selectedItem, this.Bardata[row][column]);
}
for more info read the documentation :
https://github.com/FERNman/angular-google-charts

Google Visualization Column Chart set a data column from query as role: "Style"

I have a Google Visualization Column Chart from a query that works fine. I can set the a columns with a style role after the query by using the code snippet below. It adds a new column to the query data and sets the role as "Style". This colors each of the column chart bars accordingly. But I want to be able to use one of my query columns "C" for example as the color code and not have to add it afterward. I can't seem to get this to work. Any ideas? I posted more of my code below the snippet so you can see where I'm coming from. Thanks so much guys for any help you can give. Brandon
var data = response.getDataTable();
data.addColumn({type: "string", role: "style" });
data.setCell(0,2,'red');
data.setCell(1,2,'orange');
data.setCell(2,2,'green');
data.setCell(3,2,'yellow');
// More code above this, but I ommited it.
function drawDashboard() {
var query = new google.visualization.Query(
'URL');
query.setQuery('SELECT A, B, C');
query.send(handleQueryResponse);
}
function handleQueryResponse(response) {
if (response.isError()) {
alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage());
return;
}
var data = response.getDataTable();
data.addColumn({type: "string", role: "style" });
data.setCell(0,2,'red');
data.setCell(1,2,'orange');
data.setCell(2,2,'green');
data.setCell(3,2,'yellow');
// Create a dashboard.
var dashboard = new google.visualization.Dashboard(
document.getElementById('dashboard_div'));
// Create a range slider, passing some options
var scoreSlider = new google.visualization.ControlWrapper({
controlType: 'NumberRangeFilter',
containerId: 'filter_div',
options: {
filterColumnLabel: 'Class AVG'
}
});
var ClassFilter = new google.visualization.ControlWrapper({
controlType: 'CategoryFilter',
containerId: 'Classfilter_div',
options: {
'filterColumnLabel': 'Teacher Name','ui': { 'labelStacking': 'veClasscal','allowTyping': true,'allowMultiple': true
}
}});
// Create a Column Bar chart, passing some options
var columnChart = new google.visualization.ChartWrapper({
chartType: 'ColumnChart',
containerId: 'chart_div',
options: {
title: 'Math Proficiency by Class',
height: 320,
width: 500,
chartArea:{left:"10%",top:"10%",width:"80%",height:"60%"},
hAxis: {textStyle: {fontSize:14}, title: 'Teacher Name', titleTextStyle: {fontSize:14}, textStyle: {fontSize:14}},
vAxis: {minValue: 0, maxValue: 100, title: 'Math Proficiency AVG', titleTextStyle: {fontSize:14}, textStyle: {fontSize:14}},
legend: {position: 'none'},
animation: {duration:1500, easing:'out'},
colors: ['#a4c2f4','#3c78d8']
},
view: {columns: [0, 1, 2]}
});
// Define a table
var table = new google.visualization.ChartWrapper({
chartType: 'Table',
dataTable: data,
containerId: 'table_div',
options: {
width: '400px'
},
view: {columns: [0, 1,]}
});
// Establish dependencies, declaring that 'filter' drives 'ColumnChart',
// so that the column chart will only display entries that are let through
// given the chosen slider range.
dashboard.bind([scoreSlider], [table, columnChart]);
dashboard.bind([ClassFilter], [table, columnChart]);
// Draw the dashboard.
dashboard.draw(data);
}// More code below this, but I ommited it.
I'm not sure how you would add this to a column in the query but...
using a DataView with a calculated column should work...
Assumes the value you want to test is in the second column -- index 1
var data = response.getDataTable();
var view = new google.visualization.DataView(data);
view.setColumns([0, 1, {
type: "string",
role: "style",
calc: function (dataTable, rowIndex) {
if (dataTable.getValue(rowIndex, 1) < 0.69) {
return 'color: red;';
} else if ((dataTable.getValue(rowIndex, 1) >= 0.69) && (dataTable.getValue(rowIndex, 1) <= 0.79)) {
return 'color: yellow;';
} else {
return 'color: green;';
}
}
}]);

HighCharts : Xaxis lables misplaced

I want to label xaxis with values from JSON data that is happening but it is printing it at wrong place as shown in screenshot :
Here only seven values are present its labeled in that manner but actual data is plotted by leaving a gap of one. For example at 11th there is value and then again at 13t so total seven values but taking 14 places and label properly taking there first seven places how to match labels and bar graph
Following is my code snippet :
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(key);
volumes.push(key);
my_data_list.push('Average Latency', parseInt(avg_latency));
my_data_list1.push('Read Latency', parseInt(read_latency));
my_data_list2.push('Write Latency', parseInt(write_latency));
}
$('#graphcontainer3').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Volume Level Latency'
},
yAxis: {
tickInterval: 100,
title: {
text: 'Latency(ms)'
}
},
xAxis: {
categories: volumes,
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} ms</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 2
}
},
series: [{
name: 'Average latency',
data: my_data_list,
}, {
name: 'Read Latency',
data: my_data_list1,
}, {
name: 'Write Latency ',
data: my_data_list2,
}]
});
Can anyone help me in this code to make this work fine???
I rectified the problem by myself :) It just I was giving labels two times
var obj = data[$("#host").val()].stats_vol.result.sectoutput;
var my_data_list3 = [];
var my_data_list1 = [];
var my_data_list2 = [];
var volumes = [];
for(var key in obj) {
var avg_latency = parseInt(obj[key].avg_latency);
var read_latency = parseInt(obj[key].read_latency);
var write_latency = parseInt(obj[key].write_latency);
console.log(avg_latency);
volumes.push(key);
my_data_list3.push(parseInt(avg_latency)); //here no need to give label again as it is done my volume(key)
my_data_list1.push( parseInt(read_latency));
my_data_list2.push(parseInt(write_latency));
}
This is what I was expecting as output .Hope it might be helpful for someone else hence answered.