I am trying to make a line chart by using the Google Visualization API, here is my column data definition:
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('date', 'Date');
dataTable.addColumn('number', 'Uptime');
dataTable.addColumn('string', 'Channel');
I want to group my rows by channels and these grouped channels make a line where X axis is the date and the Y axis is the uptime. I am pretty lost at the API and would be greatful of any help.
Thanks
First you create the data then you add it to the chart:
var data = new google.visualization.DataTable();
// 3 columns
dataTable.addColumn('date', 'Date');
dataTable.addColumn('number', 'Uptime');
dataTable.addColumn('string', 'Channel');
// Add 2 rows
data.addRows(2);
// setValue(row, col, value)
data.setValue(0,0, '2009-09-06');
data.setValue(0,1, 1000);
data.setValue(0,2, 'Channel1');
data.setValue(1,0, '2009-09-05');
data.setValue(1,1, 100);
data.setValue(1,2, 'Channel2');
var chart = new google.visualization.LineChart('chartDiv');
chart.draw(data, {
width: width,
height: height,
is3D: true,
title: title,
colors: colors,
enableTooltip: false,
legend: 'bottom' });
Something like that.
Are you sure you don't want google.visualization.LineChart(blah) instead of google.visualization.DataTable()? I mean, you said you wanted a line chart and the documentation says that it's LineChart which you want. Also, tinkering on the playground might be informative.
Related
I've tried every configuration possible to get a Google Area Chart to display a single point but nothing has worked. I'm also totally open to any solutions using the Google Line Chart as long as it has a filled area. However, I couldn't find a solution for making this work with a line chart either.
Already tried setting the pointSize as well as setting the pointSize conditionally if there is only a single row. Tried numerous different ways of configuring the chart including.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Updated');
data.addColumn('number', 'Amount');
data.addRow([new Date(1548266417060.704),100]);
AND
var mets = [['Updated', 'Amount'], [new Date(1548266417060.704),100]];
var data = google.visualization.arrayToDataTable(mets);
Area Chart Example JSFiddle
Line Chart Example JSFiddle
This Line Chart would need the area below the line filled in but I haven't been able to determine how to do so with this API
Example of the chart I'm trying to achieve using CanvasJs but I'm trying to implement it with Google Visualization API and allow for a single point to be shown if there is only a single point on the chart.
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100],
//[new Date(1548716961817.513),100],
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
pointSize: 5,
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I'm expecting the chart to display a single point when there is only one data row. As you can see by the JSFiddle when there is a single row nothing appears but as soon as you uncomment the second row everything works just fine.
there is a bug with the most recent version of google charts,
when the x-axis is a continuous axis (date, number, not string, etc.),
and only one row exists in the data table,
you must set an explicit view window on the axis --> hAxis.viewWindow
to use a date type with only one row,
first, use data table method --> getColumnRange
this will return an object with min & max properties for the x-axis
then we can increase the max and decrease the min by one day,
and use that for our view window.
see following working snippet...
google.charts.load('current', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100]
]);
var oneDay = (24 * 60 * 60 * 1000);
var dateRange = data.getColumnRange(0);
if (data.getNumberOfRows() === 1) {
dateRange.min = new Date(dateRange.min.getTime() - oneDay);
dateRange.max = new Date(dateRange.max.getTime() + oneDay);
}
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {color: '#333'},
viewWindow: dateRange
},
pointSize: 5
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
you'll notice if we go back to an old version ('45'),
a single date row displays without issue...
google.charts.load('45', {
packages: ['corechart']
}).then(function () {
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704),100]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {color: '#333'},
},
pointSize: 5
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
I dont know if you understod but the date format you are passing is wrong, so when you write Date() it return the current date formatted as string.
now if we understand that much then the currect way of writing the date array should be
var data = google.visualization.arrayToDataTable([
['Updated', 'Amount'],
[new Date(1548266417060.704).toString(),100],
]);
This will return the date formatted as string.
and the library will accept it.
if you are still want to pass on an object then you need to specify the dataTable column as Date.
read here for more information
https://developers.google.com/chart/interactive/docs/datesandtimes
Imagine I am drawing a line chart that includes both known (certain) values and estimated (uncertain) values. These values are all in the same series (not two different lines). This chart of projected population growth rate is a good example:
Notice how after the year 2012 or so, the line turns blue.
I have read the Customizing Lines page but it appears to change the style for the entire line, not just a segment of it.
My question is this: is it possible change the style and/or color of part of a line within the same series?
Solutions, in order of desirability:
Indicate in the value itself whether or not it is an exact or an estimated value, and to change the styling for that line segment accordingly (e.g. [(45, "exact"), (50, "exact"), (75, "estimated')] although more likely "exact" and "estimated" would be replaced with 1 and 0 respectively).
Data and styling instructions are sent to the API separately, but for the same series.
Least desired solution is one where I actually create two different series, because that will mean creating (and keeping track of) two series for each row of data, and generating the code that splits them up into the series, as well as making sure no points are displayed where there should not be data for that series.
Although I would prefer Google Visualization for its (relative) simplicity, I have some experience with D3.js and would be willing to use it instead if it is not possible to use Google Visualization.
Actually there are two solutions I was able to find:
Using DataTables and the "Certainty" role
Using DataTables with roles allows you to use data values as chart modifiers rather than actual chart data points. In this case specifically the role to use is "certainty". You supply it as an additional column after the data, and indicate that that column is a certainty role, like so:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Value');
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
['2014-12-01',100, true],
['2015-01-01',200, true],
['2015-02-01',300, true],
['2015-03-01',400, true],
['2015-04-01',500, false]
]);
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Value');
data.addColumn({type:'boolean',role:'certainty'}); // certainty col.
data.addRows([
['2014-12-01',100, true],
['2015-01-01',200, true],
['2015-02-01',300, true],
['2015-03-01',400, true],
['2015-04-01',500, false]
]);
var options = {
legend: 'none',
hAxis: { minValue: 0, maxValue: 9 },
curveType: 'function',
pointSize: 7
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
Note that you cannot control the rendering of an "uncertain" section of the line graph — Google decides this for you. If you want more control — for example, if you want it to change color as well or instead of becoming dashed, you can use styling as described below.
Styling the line of a point
Also, although not at all explicit in the Customizing Points page, you can specify styling for the line for a point as well as the point itself. If you want more customization over the styling of a segment (say its thickness or its color) you can use this option:
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Value');
data.addColumn({type:'string',role:'style'}); // style col.
data.addRows([
['2014-12-01',100, null],
['2015-01-01',200, null],
['2015-02-01',300, null],
['2015-03-01',400, null],
['2015-04-01',500, 'line { stroke-color: purple }']
]);
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Date');
data.addColumn('number', 'Value');
data.addColumn({type:'string',role:'style'}); // style col.
data.addRows([
['2014-12-01',100, null],
['2015-01-01',200, null],
['2015-02-01',300, null],
['2015-03-01',400, null],
['2015-04-01',500, 'line { stroke-color: purple }']
]);
var options = {
legend: 'none',
hAxis: { minValue: 0, maxValue: 9 },
curveType: 'function',
pointSize: 7
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.1','packages':['corechart']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
As far as I can tell you can change the color only; you can't adjust the width or the type of dashed line.
I'm using a ColumnChart to represent the elevation in a map, as suggested by Google.
However, the columns are separated by spaces, and that renders ugly white spaces between the
columns, like in Google's own example:
https://developers.google.com/maps/documentation/javascript/examples/elevation-paths
Is there a way to tell the column chart to make columns that fill up the whole space? I would like something like this:
http://4.bp.blogspot.com/-4I8oi3WqY5o/UIZnzbXql_I/AAAAAAAAAcE/GO4wl6I2-lM/s1600/Charts.png
I suspect that the only way is with lots of points.
My code:
var option = {
legend: 'none',
backgroundColor: 'transparent',
colors: ["#C9CFF5"],
titleColor: '#C9CFF5',
focusBorderColor: '#00AA00',
titleY: 'Elevation (m)',
bar: { groupWidth: '100%' }
}
// Build data
var data = new google.visualization.DataTable();
data.addColumn('string', 'Sample');
data.addColumn('number', 'Elevation (m):');
for (var i = 0; i < trackmarks.length; i++) {
data.addRow(['', trackaltis[i]]);
}
// Draw the chart using the data within its DIV.
chart = new google.visualization.ColumnChart(document.getElementById('elevation_chart'));
chart.draw(data, option);
My code is pretty standard: same as Google's, same result.
Thanks!
You can specify option:
bar: {groupWidth: "100%"}
bar.groupWidth: Percentage of the available width for each group (e.g. '20%'), where '100%' means that groups have no space between them
Update: That example uses old version of column charts which loads package columnchart
google.load("visualization", "1", {packages:["columnchart"]});
The latest code for column chart is loaded using corechart:
google.load('visualization', '1', {packages: ['corechart']});
Change that and example should work as expected without spaces.
Is it possible to develop a threshold with Google Charts?
I have a Google combo chart with 5 columns. In theory, I wanted to use the addRange formatter function to change the color of the 2nd column if it was under 50. (Basically it's a motivation tool. Your daily goal is to make atleast 50 calls. If you do not, the chart shows up as red, if you do, then it is the default color)
This is my current code that creates the chart, just not the formatting. Thanks.
// Load the Visualization API and the piechart package.
google.load('visualization', '1.0', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Rep');
data.addColumn('number', 'Yesterday');
data.addColumn('number', 'Last 7');
data.addColumn('number', 'Last 30');
data.addColumn('number', 'The Bar');
$("#data-table thead th").each(function(){
var initials = $(this).text();
var yesterday = parseInt($("." + initials + ".Yesterday").text());
var seven = parseInt($("." + initials + ".seven").text());
var thirty = parseInt($("." + initials + ".thirty").text());
data.addRow([initials, yesterday, seven, thirty, 50]);
});
// Set chart options
var title = $("#data-table caption").text();
var options = {'title':title,
seriesType: 'bars',
series: {3: {type: "line"}},
hAxis: {title: 'Rep'},
vAxis: {title: 'Outbound Calls'}
};
var formatter = new google.visualization.TableColorFormat();
formatter.addRange(50,0, 'red', '#000');
formatter.format(data, 1);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.ComboChart(document.getElementById('call-log'));
chart.draw(data, options);
}
The easiest way to do this is to do a quick check on your data, and set a variable for the color of series two based on what the value of that column is.
So currently you have the following options code:
var options = {'title':title,
seriesType: 'bars',
series: {3: {type: "line"}},
hAxis: {title: 'Rep'},
vAxis: {title: 'Outbound Calls'}
};
If you change this slightly, you can make series 2 colored based on a variable:
var options = {'title':title,
seriesType: 'bars',
series: {
3: {type: "line"}
// set the color of column 2 (series #1) via variable
1: {color: colorvar}
},
hAxis: {title: 'Rep'},
vAxis: {title: 'Outbound Calls'}
};
Then you can just create a javascript function to determine what the value for column 2 is, and color appropriately:
var colorvar = "#FF0000";
if (data.getValue(0,1) >= 50)
colorvar = "#000000";
This way, if the value is under 50, it will be read. Otherwise it will change to black. Then when you create the options, it will use whatever color is dictated by this function. That way you can color based on the value in column 2.
I need remove first empty string in tooltip.
I'm used formater, for change first string to '', but I'm can't remove it. If I change '' to null then in first string shows first column data.
Code:
var data = new google.visualization.DataTable();
data.addColumn('string', 'State');
data.addColumn('number', 'TempNumber');
data.addColumn({
type: 'string',
role: 'tooltip'
});
data.addRows([
['Ohio', 0, 'Ohio'],
...
]);
var options = {
width: 580,
region: 'US',
resolution: 'provinces',
colorAxis: {colors: ['#abb7df']},
legend: 'none'
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
var formatter = new google.visualization.PatternFormat('');
formatter.format(data, [0,1,2]);
chart.draw(data, options);
Unfortunately there is no easy way to currently do this (without drawing your own tooltip function to draw the boxes). In the future, hopefully they will implement isHtml: true to geocharts, but right now it isn't supported.
Tooltip cannot do what you want it to do in its current implementation. You can reduce text size, but that will also reduce the size of the text you want shown. You can change color, but again it affects the entire tooltip. There isn't really much you can do to fix the issue rather than implement your own form of tooltipping (creating a function that will take the column 0 value of whatever your mouse is over, and display it either in a separate in the page, or have it calculate where your mouse is and show it there).