I'm trying to configure to my google candlestick chart a grouping format by date, as I saw it required a continuous axis (all the hAxis options are followed by: This option is only supported for a continuous axis.)
I know i need to add a continuous axis, but HOW am i doing this ?? I was trying for 2 days to play with the settings without any luck.
Build a datatable instance without using the arrayToDataTable() method or it will raise an exception. Define your horizontal axis as 'date' and use Date() objects instead of strings.
var data = new google.visualization.DataTable()
data.addColumn('date', 'Date');
data.addColumn('number', 'Whatever');
rows = [
[new Date('2009-10-01'), 1230],
[new Date('2009-11-01'), 1290],
[new Date('2012-02-01'), 3690],
];
data.addRows(rows);
It should be enough.
Related
Here is my data:
dataToDisplay=[[156,"2013-12-01","note one"],
[206,"2013-12-02","note two"],
[280,"2013-12-03","note three"],
[320,"2013-12-04","note four"],
[0,"2013-12-05",""]]
Here is the code to make a line chart:
chartData = new google.visualization.DataTable();
chartData.addColumn('number', 'Miles');
chartData.addColumn('string', 'Date');
chartData.addColumn({type:'string', role:'annotationText'});
chartData.addRows(dataToDisplay);
graphTitle = 'Mileage'
var options = {
title: graphTitle,
height:600
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(chartData, options);
and the error:
"Data column(s) for axis #0 cannot be of type string"
I'm at a loss as to what's going on. Which column is axis #0?
Also, is there a way to build a line graph with annotations using something like:
var chartData = google.visualization.arrayToDataTable(dataArray);
If so, how would dataArray have to be constructed?
LineChart's accept strings only as annotation columns or domain columns. The first column is the domain column, and annotation columns have to be specified as such. In your case, the "date" column is causing the problem, as it is the second column, and therefore is expected to be either a data ("number" type) column or an annotation column. You did not specify it as an annotation column, which is why you get the error.
Is your intent to have the dates be annotations or values? if they are intended to be values, you must put them in the first column:
chartData = new google.visualization.DataTable();
chartData.addColumn('string', 'Date');
chartData.addColumn('number', 'Miles');
chartData.addColumn({type:'string', role:'annotation'});
In order to use the "annotationText" data role, the preceeding column must be an "annotation" role column. The "annotation" role creates a text label on the chart at the associated data point, and the "annotationText" role creates a tooltip to show when the user hovers over the label.
I have a line chart where we plot some numbers against a datetime value on x-axis. Since, using datetime value on column type renders it a continuous axis, the column labels are auto generated.
We get only the time component as the column labels but not the date. Is there anything I can do to get the entire date time as the label?
(NOTE: I do not want to change the data type to string as I do not want even spacing in data points.)
Yes. You need to look at formatters which use a subset of the ICU SimpleDateFormat.
Here is an example of how they work:
function drawVisualization() {
// Create and populate the data table.
var data = new google.visualization.DataTable();
data.addColumn('date', 'Date');
data.addRows([
[new Date(2012,1,5)],
[new Date(2012,2,10)],
[new Date(2012,3,15)],
[new Date(2012,4,20)]
]);
alert(data.getFormattedValue(3,0));
var formatter1 = new google.visualization.DateFormat({pattern: 'yyyy, MMM'});
formatter1.format(data,0);
alert(data.getFormattedValue(3,0));
}
Adjust to fit your data and needs, and presto! You have it working.
When I use a column type of date, the first and last bars in the ColumnChart are cut in half. It seems to be rendering from mid-bar. It doesn't do this with non-date sets of data.
Is there any way to fix this so that the complete bars are rendered, with some extra padding?
http://jsfiddle.net/7tHVN/
Setting the viewWindowMode does work for dates, apparently. Adding the following to my chart options, where the min and max are dates prior to and beyond the 1st and last date values, worked for me, at least.
'hAxis': {'viewWindowMode': 'explicit', 'viewWindow': {'max':new Date('2012-10-02'), 'min':new Date('2007-07-02')}}
See also: Column Chart crops the end bars in the Google forums.
I had this exact problem (my labels were also weirdly misaligned) and it drove me crazy trying to figure it out. hAxis.viewWindowMode usually fixes issues like this, but it's not possible to use this with date values.
What I ended up doing was just scrapping the date type entirely, specifying the string type for that column instead, and converting each JS date object to a string representation before adding it to the DataTable, thusly:
data.addColumn('string', 'Date');
data.addColumn('number', 'Performance');
var dates = [new Date('2012-4-12'),
new Date('2012-4-13'),
new Date('2012-4-14')];
var performance = [59, 35, 86];
var dateString;
for (var i=0; i<dataForChart.length; i++) {
dateString = (dates[i].getMonth()+1)+'/'+ // JS months are 0-indexed
dates[i].getDate()+'/'+
dates[i].getYear();
data.addRow([dateString,
performance[i]]);
}
This forces the chart to render with a discrete rather than continuous axis, which fixes the cut-off bars problem. As long as your data and dates are spaced along even intervals (once a day, once a week, etc.) and you pass them in in the proper order, this approach should work.
There's more info on discrete vs. continuous axes in the Google Viz docs: https://google-developers.appspot.com/chart/interactive/docs/customizing_axes
Easy Fix here 😎
If you double click on the first column to access the Format Data Point you can widen the individual column width to match the same visibility as the other columns. Same applies to the last column when 'cut off' due to date and axis
This looks like a bug on Excel, easy fix, change the graph type to stacked bar, then switch back to stacked column, and your graph will be fixed.
I have a Column Chart with an x-axis value which is a date. This chart worked this morning but is suddenly broken and displaying "Bars series with value domain axis is not supported." as an error message. The website in question hasn't been updated in weeks.
My DataTable construction code looks like:
var data= new google.visualization.DataTable({
"cols":[{"label":"Date","type":"date"},{"label":"New Users","type":"number"}],
"rows":[{"c":[{"v":new Date(1325656800000),"f":null},{"v":1355,"f":null}]}]
});
What can I do to my code to fix this?
It's not a bug. Google Visualisation API has changed.
At http://code.google.com/apis/chart/interactive/docs/customizing_axes.html#Help they post some solutions to this problem. Using option:
strictFirstColumnType: false
can only be used as a temporary solution. Google says:
However, please bare in mind that this option is only available for limited time and will be removed in the near future.
The recommended solution is that you change your Date fields on x axis to String. I've achieved this by using formatter before adding value to the DateTable object.
var formatterMoney = new google.visualization.NumberFormat({suffix: ' zł', decimalSymbol: ',', groupingSymbol: ' '});
var formatterDate = new google.visualization.DateFormat({pattern: 'dd.MM.yyyy'});
var data = new google.visualization.DataTable();
data.addColumn('string', 'order date'); //used to be date field here
data.addColumn('number', 'total amount');
data.addRow([formatterDate.formatValue(new Date('2011-12-20')),971793.93]); //used to be Date object, now is Date formated as String
data.addRow([formatterDate.formatValue(new Date('2011-11-30')),1.0]);
data.addRow([formatterDate.formatValue(new Date('2011-11-17')),1.0]);
data.addRow([formatterDate.formatValue(new Date('2011-10-27')),1.72]);
data.addRow([formatterDate.formatValue(new Date('2011-10-26')),10.27]);
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
formatterMoney.format(data, 1);
chart.draw(data, {width: window.width, height: 400, hAxis: {direction: -1}});
The problem is with the Date fields. I've converted the date field to a String and I'm using a String now. In case you are using formatters, you can format the value before supplying it to the DataTable:
formatter.formatValue(date)
I'm guessing this is a bug; I'll try to file a bug report.
I am looking to create a Google charts API dashboard with filtering but I would like to chart the data based on grouped data. For example, I can create a datatable such as this:
salesman cust_age cust_sex quantity
Joe 21 Male 3
Joe 30 Female 10
Suzie 40 Female 2
Dave 15 Female 5
Dave 30 Male 10
I can appropriately create a dashboard that creates two controls (for cust_age and cust_sex) and any number of output graphs and tables all pulling from an external data source - this is pretty stock stuff, see http://code.google.com/apis/chart/interactive/docs/gallery/controls.html
The problem that I am having is how to show all charts by grouped values. Using a pie chart as an example, without any filters there are 5 slices of the pie (Joe, Joe, Suzie, Dave, Dave) - I would like to see only three (Joe, Suzie Dave). Of course, when a control is applied everything should update.
In other words, the filters should act on the original datatable, but the charts should be based on a grouped datatable.
I would guess that we could use the grouping function:
http://code.google.com/apis/ajax/playground/?type=visualization#group
however I cannot seem to bind the filters to the larger datatable, update the grouped table, and then draw the charts based on the grouped table.
Any thoughts?
I found a workaround, you should use the chartWrapper without the dashboard, so you can pass a dataTable as parameter:
var $pieChart = new google.visualization.ChartWrapper({
'chartType': 'PieChart',
'containerId': 'pie_chart',
'options': {
'width': 300,
'height': 300,
},
//group the data for the pie chart
'dataTable' : google.visualization.data.group($dataTable, [0],
[{'column': 3, 'aggregation': google.visualization.data.sum, 'type': 'number'}])
});
$pieChart.draw();
$tableWrapper = new google.visualization.ChartWrapper({
'chartType': 'Table',
'containerId': 'table_data'
});
var $genderPicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'gender_filter',
'options': {
'filterColumnIndex': '2',
'useFormattedValue' : true,
'ui': {
'allowTyping': false,
'allowMultiple': false,
'labelStacking': 'vertical'
}
}
});
new google.visualization.Dashboard(document.getElementById('table_dashboard')).
bind([$genderPicker], [ $tableWrapper]).
draw($dataTable);
Then, you should add a callback to your controls so whenever the control changes the charts outside of the dashboard will be updated, like a manual binding, let's assume that the control for cust_sex is $genderPicker and the ChartWrapper table object is $tableWrapper:
google.visualization.events.addListener($genderPicker, 'statechange',
function(event) {
// group the data of the filtered table and set the result in the pie chart.
$pieChart.setDataTable( google.visualization.data.group(
// get the filtered results
$tableWrapper.getDataTable(),
[0],
[{'column': 3, 'aggregation': google.visualization.data.sum, 'type': 'number'}]
));
// redraw the pie chart to reflect changes
$pieChart.draw();
});
The result: whenever you chose male, female or both the pie chart will reflect the filtered results grouped by name. Hope it helps someone and sorry for my broken english.
another way to do it, is to use the 'ready' event of the dashboard object, then create a chart or table in there based on a grouping done to the main table of the dashboard.
eg:
//create datatable, filter elements and chart elements for the the dashboard then:
dash=new google.visualization.Dashboard(document.getElementById(elId));
google.visualization.events.addListener(dash, 'ready', function() {
//redraw the barchart with grouped data
//console.log("redraw grouped");
var dt=mainTable.getDataTable();
var grouped_dt = google.visualization.data.group(
dt, [0],
[{'column': 7, 'aggregation': google.visualization.data.sum, 'type': 'number'}]);
var mainChart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'barChart',
'options': {
'height':500,
'chartArea':{'left':200}
},
//view columns from the grouped datatable
'view': {'columns': [0, 1]},
'dataTable':grouped_dt
});
mainChart2.draw();
});
dash.bind(
[lots,of,filter,elements],
[lots,of,chart,elements]
);
dash.draw(data)
After a long R&D, I found the solution fot this problem. For the fix, I used two event listeners in which one is ready event and other is statechange event as,
google.visualization.events.addListener(subdivPicker, 'ready',
function(event) {
// group the data of the filtered table and set the result in the pie chart.
columnChart1.setDataTable( google.visualization.data.group(
// get the filtered results
table.getDataTable(),
[0],
[{'column': 2, 'aggregation': google.visualization.data.sum, 'type': 'number'}]
));
// redraw the pie chart to reflect changes
columnChart1.draw();
});
google.visualization.events.addListener(subdivPicker, 'statechange',
function(event) {
// group the data of the filtered table and set the result in the pie chart.
columnChart1.setDataTable( google.visualization.data.group(
// get the filtered results
table.getDataTable(),
[0],
[{'column': 2, 'aggregation': google.visualization.data.sum, 'type': 'number'}]
));
// redraw the pie chart to reflect changes
columnChart1.draw();
});
Find my initial (problematic) sample here and fixed (solved) sample here
Read this thread: How to not display the data table (read at least the first two posts - the rest are really only important if you are dealing with large data sets).
Basically, you have to use an intermediary chart (tables are a good choice, because they are relatively fast to write and render, with a lower memory footprint than most charts) that is completely hidden from the users. You bind the category picker to this chart in the dashboard. Then you set up an event handler for the picker's "statechange" event that takes the data, groups it into a new DataTable, and draws the PieChart based on the grouped data.