Stop google chart from adding dates in between values - javascript

I'm trying to draw ComboChart. My problem is that chart keep adding dates in between values, which makes chart unnecessary big:
My code:
var chart;
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawVisualization);
function drawVisualization() {
var graphData = [{"date":new Date(1470903103000),"count1":47,"count2":3},
{"date":new Date(1472134276000),"count1":92,"count2":20},
{"date":new Date(1472198154000),"count1":92,"count2":15}];
rowCount = graphData !== undefined ? graphData.length : 0;
var data = new google.visualization.DataTable();
data.addColumn('datetime', 'Date');
data.addColumn('number', 'Count1');
data.addColumn("number", "Count2");
for (var i = 0; i < rowCount; i++) {
var gDate = graphData[i].date;
var gCount1 = graphData[i].count1;
var gCount2 = graphData[i].count2;
data.addRow([ gDate, gCount1, gCount2]);
}
var options = {
title : 'Overview',
vAxis: {title: 'Count'},
hAxis: {title: 'Date'},
seriesType: 'bars',
series: { 1: { type: 'line' } },
//chartArea: { left: 0, top: 0, width: "80%", height: "80%" },
height: 200,
width: 500
};
chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
or go to fiddle

Solution is pretty simple, I simply had to send string instead of dateTime:
data.addColumn('datetime', 'Date'); => data.addColumn('string', 'Date'); and var gDate = graphData[i].date; => var gDate = graphData[i].date.toString();

Related

How to change line color based on the value [google charts]

I have a chart to represent some temperatures of a specific place, I am using Google Chart tools (area chart), and Im trying to put a diferent color (orange) if the temperature is greater than 25 degrees
Javascript code
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Data');
data.addColumn('number', 'Temperatura ÂșC');
data.addColumn({ type: 'number', role: 'annotation' });
var array = JSON.parse('<%=jsonStringTemp%>');
console.log(array);
for(var i=0; i<array.length;i++){
var array2=[];
for (j = 0; j < array[i].length; j++){
if (typeof array[i][j]==='string') {
if (j !== 0) {
array[i][j]=parseInt(array[i][j], 10)
}
}
array2.push(array[i][j])
}
data.addRow(array2)
}
console.log(data)
var options = {
title: 'Temperatura',
hAxis: {title: 'Data', titleTextStyle: {color: '#333'}},
vAxis: { minValue: 0 },
series: {
0: {
color: 'green'
},
},
pointSize: 6
};
;
var chart = new google.visualization.AreaChart(document.getElementById('linechart_material'));
chart.draw(data, options);
}
output
Is it possible to do it? And How?

Changing the number format in google charts graphs

I have a problem to change number format in my google chart.
I checked stackoverflow topic and I found it : http://jsfiddle.net/h5ea6xqu/
My problem is simple, I want exactly the same thing, but it doesn't working.
I have "," instead space for my grouping symbol... If someone have the solution, it would be awesome.
my problem
My code :
function drawChart($id) {
var id=$id;
var kwexist = (id + "_kw_exist");
var kwexistvariable = $("#"+kwexist).html();
var kwled = (id + "_kw_led");
var kwledvariable = $("#"+kwled).html();
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }, { role: 'annotation' } ],
['Existant kWh', parseFloat(kwexistvariable), '#3B7CC9', parseFloat(kwexistvariable)],
['LED kWh', parseFloat(kwledvariable), '#3B7CC9' , parseFloat(kwledvariable)]
]);
var options = {
};
var numberFormat = new google.visualization.NumberFormat({
groupingSymbol: ' '
})
numberFormat.format(data, 1);
var chart_div = document.getElementById('chart_div_kw');
var chart = new google.visualization.ColumnChart(chart_div);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div.innerHTML = chart.getImageURI();
var testokok = chart.getImageURI();
console.log(chart_div.innerHTML);
});
chart.draw(data, options);
}
not sure i follow the question exactly
but if you want to format the number shown on the bar (annotation)
also format that column...
numberFormat.format(data, 3);
see following working snippet...
google.charts.load('current', {
callback: drawChart,
packages: ['corechart']
});
function drawChart($id) {
var data = google.visualization.arrayToDataTable([
['Element', 'Density', { role: 'style' }, { role: 'annotation' } ],
['Existant kWh', parseFloat(10000), '#3B7CC9', parseFloat(10000)],
['LED kWh', parseFloat(15000), '#3B7CC9' , parseFloat(15000)]
]);
var options = {
};
var numberFormat = new google.visualization.NumberFormat({
groupingSymbol: ' '
});
numberFormat.format(data, 1);
numberFormat.format(data, 3);
var chart_div = document.getElementById('chart_div');
var chart = new google.visualization.ColumnChart(chart_div);
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Unable to display actual chart using Google API in Javascript

I am displaying a chart using Google API and I am getting a chart but it is not displaying that line in the graph,
This is the code I am trying with, I am using array data for charts,
var jsonlength = data.feed.entry.length;
var timestamp = new Array(jsonlength);
var temperature = new Array(jsonlength);
var tempid = new Array(jsonlength);
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = ((data.feed.entry[i].gsx$temperaturevalue.$t));
}
google.charts.load('current', {packages: ['corechart', 'line']});
google.charts.setOnLoadCallback(drawBasic);
function drawBasic() {
var data = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
console.log(i);
data1.addRows(i,data.feed.entry[i].gsx$temperaturevalue.$t);
//Here I can display all those values, But still not getting the chart, Though I have given proper values, Help me here
console.log(data.feed.entry[i].gsx$temperaturevalue.$t);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);
This is the output I am getting without a line, Please help me I am new to this
Output without a line in the graph
most likely is due to 'string' values vs. number
try this...
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
here...
for (var i = 0; i < jsonlength; i++) {
timestamp[i] = ((data.feed.entry[i].gsx$timestamp.$t));
temperature[i] = (parseFloat(data.feed.entry[i].gsx$temperaturevalue.$t));
}
EDIT
here, you create data
var data = new google.visualization.DataTable();
but then you're adding columns to data1 ???
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
try syncing up the variable names and check addRow below...
var data1 = new google.visualization.DataTable();
data1.addColumn('number', 'X');
data1.addColumn('number', 'X');
for (var i = 0; i < jsonlength; i++) {
// use addRow -- which takes an array
data1.addRow([i,data.feed.entry[i].gsx$temperaturevalue.$t]);
}
var options = {
hAxis: {
title: 'Date'
},
vAxis: {
title: 'Temperature'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data1, options);

How can I draw two material charts with the Google Charts API without one being empty?

I'm trying to draw two charts using the Google Charts API. I set up my HTML like this:
<div id="page_views" data-title="{{ report['page_views']['title'] }}" data-labels="{{ report['page_views']['labels'] }}" data-rows="{{ report['page_views']['rows'] }}"></div>
<div id="event_views" data-title="{{ report['event_views']['title'] }}" data-labels="{{ report['event_views']['labels'] }}" data-rows="{{ report['event_views']['rows'] }}"></div>
where the data attributes are filled during template rendering. I then use the following javascript to attempt to draw my charts:
google.load('visualization', '1.0', {packages: ['line']});
google.setOnLoadCallback(drawCharts);
function drawPageViews() {
var data = new google.visualization.DataTable();
var page_views = document.getElementById("page_views");
var labels = eval(page_views.dataset.labels);
data.addColumn('number', "Day");
for(var i = 0; i < labels.length; i++) {
data.addColumn('number', labels[i]);
}
var rows = eval(page_views.dataset.rows);
data.addRows(rows);
var options = {
chart: {
title: page_views.dataset.title
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('page_views'));
chart.draw(data, options);
}
function drawEventViews() {
var data = new google.visualization.DataTable();
var event_views = document.getElementById("event_views");
var labels = eval(event_views.dataset.labels);
data.addColumn('number', "Day");
for(var i = 0; i < labels.length; i++) {
data.addColumn('number', labels[i]);
}
var rows = eval(event_views.dataset.rows);
data.addRows(rows);
var options = {
chart: {
title: event_views.dataset.title
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('event_views'));
chart.draw(data, options);
}
function drawCharts() {
drawPageViews();
drawEventViews();
}
The result that I get is that one of the charts is drawn while the other contains an SVG with an empty tag and nothing else inside. Which chart gets drawn is random. Commenting out either draw function makes the other single chart draw as expected.
It seems like there must be some sort of shared global state or variable but it looks to me like everything is defined in the different draw functions. When I look up similar questions people offer solutions which look very much like what I'm doing. What am I missing?
It seems this behavior is related with draw function, in particular it occurs once multiple charts is rendered on the page.
According to the documentation:
The draw() method is asynchronous: that is, it returns immediately,
but the instance that it returns might not be immediately available.
For rendering multiple charts on the page you could consider the following approach: render the next chart once the previous one is rendered, this is where ready event comes to the rescue.
Having said that the solution would be to replace:
function drawCharts() {
drawPageViews();
drawEventViews();
}
with
function drawCharts() {
drawPageViews(function(){
drawEventViews();
});
}
where
function drawPageViews(chartReady) {
//...
var chart = new google.charts.Line(document.getElementById('page_views'));
if (typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
and
function drawEventViews(chartReady) {
//...
var chart = new google.charts.Line(document.getElementById('event_views'));
if (typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
Working example
google.load('visualization', '1.0', { packages: ['line'] });
google.setOnLoadCallback(drawCharts);
function drawPageViews(chartReady) {
var data = new google.visualization.DataTable();
var page_views = document.getElementById("page_views");
var labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
data.addColumn('string', 'Day');
data.addColumn('number', 'PageViews');
var rows = new Array();
for (var i = 0; i < labels.length; i++) {
rows.push([labels[i], getRandomInt(0, 100)]);
}
data.addRows(rows);
var options = {
chart: {
title: 'Page views'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('page_views'));
if(typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
function drawEventViews(chartReady) {
var data = new google.visualization.DataTable();
var event_views = document.getElementById("event_views");
var labels = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
data.addColumn('string', 'Day');
data.addColumn('number', 'EventViews');
var rows = new Array();
for (var i = 0; i < labels.length; i++) {
rows.push([labels[i], getRandomInt(0, 100)]);
}
data.addRows(rows);
var options = {
chart: {
title: 'Event views'
},
width: 900,
height: 500
};
var chart = new google.charts.Line(document.getElementById('event_views'));
if(typeof chartReady !== 'undefined') google.visualization.events.addOneTimeListener(chart, 'ready', chartReady);
chart.draw(data, options);
}
function drawCharts() {
drawPageViews(function(){
drawEventViews();
});
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<div id="page_views"></div>
<div id="event_views"></div>

setting google chart multiple axes from dynamically generated data

I'm trying to replicate the following code from a working example:
series: {0: {targetAxisIndex:0},
1: {targetAxisIndex:0},
2: {targetAxisIndex:1},
This is for setting which y-axis is used to plot different columns from a dataTable on a Google chart.
However I have a variable number of columns (based on user input), therefore am collecting an array of the required axis (the axisAssignment Array in the below example).
My code is below:
var series = {};
for (i=0;i<axisAssignment.length;i++)
{
series[i] = {targetAxisIndex: axisAssignment[i]};
}
return series;
However, all of my data is only being written to the left axis, despite the debugger suggesting that the object is correct. My option code is below:
var options =
{
hAxis: {title: xTitle},
vAxes: {0: {title: y1Type},
1: {title: y2Type}
},
series: calculateSeries(),
pointSize: 1,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
Any assistance would be greatly apreciated.
Thanks
Tom
edit: whole file for reference (it's a work in progress so a bit of a mess I'm afraid)
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart());
function drawChart()
{
var title = "Node: "+currentNode;
var xTitle = "Date";
var yTitle = titles[currentVariable];
if (totalData !== null)
{
var tempData = newData();
var tempData2 = totalData;
dataArray[dataCount] = tempData;
var joinMark = countArray(dataCount);
totalData = google.visualization.data.join(tempData2,tempData,'full',[[0,0]],joinMark,[1]);
dataCount = dataCount+1;
}
else
{
totalData = newData();
dataArray[dataCount] = totalData;
dataCount = 1;
}
var options =
{
hAxis: {title: xTitle},
vAxes: {0: {title: y1Type},
1: {title: y2Type}
},
series: calculateSeries(),
pointSize: 0.5,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
var chart = new google.visualization.ScatterChart(document.getElementById('graph'));
console.log(calculateSeries());
chart.draw(totalData, options);
function countArray(count)
{
var arrayCount= new Array();
if (count===1)
{
arrayCount[0] = count;
}
else
{
for (var i=0;i<count;i++)
{
var temp = i+1;
arrayCount[i] = temp;
}
}
return arrayCount;
}
function calculateSeries()
{
var series = {};
for (i=0;i<axisAssignment.length;i++)
{
series[i] = {targetAxisIndex: axisAssignment[i]};
}
return series;
}
function newData()
{
var dataType = dataIn[0];
dataIn.shift();
var axis = dataSelect(dataType);
axisAssignment.push(axis);
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addColumn('number', "Node: "+currentNode+": "+titles[currentVariable]);
var num = (dataIn.length);
data.addRows(num/2);
var i = 0;
var j = 0;
while (i<num)
{
var d = (dataIn[i]);
if (i%2===0)
{
d = new Date(d);
data.setCell(j,0,d);
i++;
}
else
{
data.setCell(j,1,parseFloat(d));
i++;
j++;
}
}
return data;
}
function dataSelect(type)
{
var axisNumber;
if (y1Type === null || y1Type === type)
{
y1Type = type;
axisNumber = 0;
}
else if (y2Type === null || y2Type === type)
{
y2Type = type;
axisNumber = 1;
}
else
{
alert("You already have 2 axes assigned.\n\nPlease clear the graph \nor select more objects of \ntype"+y1Type+" or \ntype "+y2Type+" to continue.");
axisNumber = null;
}
return axisNumber;
}
}
Ok, it seems that it's an issue with my choice of ScatterChart,
var options =
{
hAxis: {title: xTitle},
series: calculateSeries(),
vAxes: {0: {title: y1Type },
1: {title: y2Type}
},
pointSize: 0.5,
legend: {position: 'top', textStyle: {fontSize: 10}}
};
var chart = new google.visualization.LineChart(document.getElementById('graph'));
chart.draw(totalData, options);
I've changed it to LineChart and it's working fine, by keeping the pointSize option, the appearance is almost completely unchanged. Thanks for your help juvian.

Categories