Welcome back to Chart Tuning! In this second half of the series we will show you how to define the different views for our chart and implement the zooming functionalities.
Before diving into the code explanation, check out the live example and the source code of the example chart if you haven’t yet.
Now that all our data is in place, we can get the visualization started. First we create a ChartWrapper by calling getChartWrapper. After setting the data table for our chart, we set the visualization mode to month and we can draw the chart.
ChartWrapper
getChartWrapper
The function setMonthView shows:
setMonthView
The function setWeekView shows how to set the view window so that we show seven points centered on the user’s selection and how to visualize all the columns, as per requirement of the week view.
setWeekView
Google charts can fire events for which you can listen. Events can be triggered by user actions: for example a user clicks on a chart. This comes in handy for our zooming functionality, as we need to intercept a user clicking a column in the chart.
To listen for these clicks, we add an event listener on the chart, and call the setWeekView function when the select event occurs.
And that’s it, our chart is ready!
Have you noticed the graceful transition of the chart when using the zoom functionality? Transition animations are one of the latest additions to the Google Chart Tools, and you can experiment with different transition behaviors to properly tune your chart!
The zooming effect is nice to see, and when we’re in week view, we can use it to scroll the chart without changing a single line of code: if we click on one of the columns, the view centers on the selected point.
Thinking about the user experience, we have to consider that it might not be clear for our user that the zooming effect is activated when clicking on one column, or that they can still scroll the chart by clicking the other columns.
We can provide a better user experience by adding a button to toggle between week and month view; when in week view, we can add two arrow buttons to allow the user to scroll to the previous or the following week.
Why don’t you try to modify the source code to implement this feature request? We will add our solutions to the example chart source code on February 21, and then discuss possible solutions and other improvement ideas during the AdSense Management API Office Hours scheduled for that day.
For any questions or suggestions, don’t hesitate to engage with us in our forums:
Update: our solution has been added to the AdSense API showcase project.
- Silvano Luciani, AdSense API Team
During Chart Tools Week, we showed you how to create a basic dashboard for AdSense reporting using the AdSense Management API and Google Chart Tools.
In this new two-part series, we’ll examine more advanced charting techniques that will improve the look and feel of our chart as well as enable user interactivity.
We’ll also show you how to use the Google Closure Library to ease some of the data manipulation tasks when writing a JavaScript application.
Our goal is to produce this Column Chart showing the earnings per day for the current month. We also want a zoom feature, with the following requirements:
Dive with us into the source code of our example chart to see how easy this task can be! You can find instructions on how to setup the example project to use Closure in the README file.
After the Google API JavaScript client has loaded, the OAuth 2.0 flow completes, and the user logs in, makeApiCall is called to start the generation of the chart.
makeApiCall
The first thing we do in makeApiCall is fetch our data from the AdSense Management API. We want DATE to be the dimension for our report, and EARNINGS, PAGE_VIEWS_RPM and AD_REQUEST_RPM as our metrics. To determine start date and end date, we can use the Google Closure Library as shown in the getRequestParams function. After that we are ready to send our request.
DATE
EARNINGS
PAGE_VIEWS_RPM
AD_REQUEST_RPM
start date
end date
getRequestParams
Once we have the data, the next step is to format it into a DataTable that will be consumed by our chart. The addTableHeaders function shows how to add the columns that we need for our chart. Two column declarations might catch your attention:
DataTable
addTableHeaders
dt.addColumn({'type': 'string', role: 'tooltip'}); dt.addColumn({'type': 'boolean', role:'certainty'});
For these columns we are using DataTable Roles, an experimental feature of the Google Chart Tools that can be used to describe the purpose of the data in a column. Using the tooltip role we can edit the text to display when the user hovers over data points. Using the certainty role we can indicate whether a data point is certain or not, and have the column visualized in a different way accordingly.
tooltip
certainty
After defining the columns, we can add rows of data to our DataTable. To do this, we need to keep the following into account:
For the first point, we need to iterate through the values returned from the API. If a DATE is not present in the response, we add a row with value zero for all the metrics for that DATE to the table. To satisfy the second point, we need to check if the current day of the iteration is the current day of the month or a day in the future. If it is in the future, we need to flag the row as uncertain.
Remember that the rows part of the API response will be an array similar to:
"rows": [ ["2012-01-03", "28", "46", "41"], ... ["2011-11-07", "2", "3", "3"] ]
The function addTableRows implements the data manipulation algorithm, using Closure to help out with dates formatting and days iteration.
addTableRows
The function formatRow shows how to create rows for our DataTable and add data for our tooltip and certainty columns. In the example, we have built the tooltips to show the full name of the day of the week for each data point, to help the user to better contextualize the value.
formatRow
At the end of day one, we have all the data ready to be visualized. Tomorrow we’ll see more on how to define our week and month views and implement the zooming functionalities.
In the meantime, don’t hesitate to ask your questions, leave your suggestions, and engage with us in our forums:
Thanks for joining us for Chart Tools week on the blog, where we're sharing ways to use Google Chart Tools. In the fourth and last part of this series, we’ll examine how to organize and manage multiple charts that share the same underlying data using dashboards and controls.
The last request of the CEO is to be able to interact with the data: he wants to filter the line chart and the column chart by expressing a range of page views.
What we need to do now is compose the 2 charts into a Dashboard object, following these steps:
Dashboard
To create a Dashboard, we need the charts to share the same underlying data. For this reason, we will combine the requests for the line and the column chart into a single request:
The result will be similar to:
result = { "kind": "adsense#report", "totalMatchedRows": "9", "headers": [ {...} ], "rows": [ ["2011-01", "28", "46", "41", "165"], ... ["2011-11", "2", "3", "3", "3"] ], "totals": ["", "241", "278", "264", "825"], "averages": ["", "26", "30", "29", "91"] }
Now we can create our DataTable, adding columns for all the metrics:
var data = new google.visualization.arrayToDataTable( [['Month', 'PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS']].concat(resp.rows));
The next step is to create the wrappers:
var lineChartWrapper = new google.visualization.ChartWrapper({ chartType: 'LineChart', options: {'title': 'Ad requests trend - Year 2011'}, containerId: 'line_chart_div', view: {'columns': [0, 2]} }); var columnChartWrapper = new google.visualization.ChartWrapper({ chartType: 'ColumnChart', options: {'title': 'Performances per month - Year 2011'}, containerId: 'column_chart_div', view: {'columns': [0, 1, 3, 4]} });
There are two important differences between creating wrappers for a dashboard and wrappers for standalone charts:
Time to create the control!
Let’s create the control wrapper for our number range filter for the ad requests:
var adRequestsSlider = new google.visualization.ControlWrapper({ 'controlType': 'NumberRangeFilter', 'containerId': 'ad_requests_filter_div', 'options': { 'filterColumnLabel': 'Ad requests', } });
The option container_id specifies the element of the page where the filter will be drawn into, while filterColumnLabel tells the filter which column to target.
container_id
filterColumnLabel
Remember that we need a DataView to convert our string field to numeric fields:
DataView
var view = new google.visualization.DataView(data); view.setColumns([ 0, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 1))}, type:'number', label:'Page views'}, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 2))}, type:'number', label:'Ad requests'}, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 3))}, type:'number', label:'Matched ad requests'}, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 4))}, type:'number', label:'Individual ad impressions'}, ]);
Creating the Dashboard, binding the control to the charts and drawing the dashboard is as easy as the following:
var dashboard = new google.visualization.Dashboard( document.getElementById('dashboard_div')) .bind(adRequestsSlider, [lineChartWrapper, columnChartWrapper]) .draw(view);
dashboard_div is the element of the page that acts as container for the Dashboard:
dashboard_div
<div id="dashboard_div"> <!--Divs that will hold each control--> <div id="ad_requests_filter_div"></div> <!--Divs that will hold each chart--> <div id="line_chart_div"></div> <div id="column_chart_div"></div> </div>
And it’s done! Our Dashboard is ready. Check the live example and the source code for today!
Well done -- our dashboard is ready and the CEO is happy with his new tool! Now you can relax and play foosball!
If you want to know more about our APIs, check the documentation pages:
And if you have any additional questions, don’t hesitate to engage with us in our forums:
You can also join us in one of our AdSense API Office Hours on Google+ Hangouts. Check the schedule for the upcoming Office Hours in our Google Ads Developer Blog.
Lastly, a public service announcement: thanks Riccardo for your help!
Welcome back to Chart Tools week here on the blog, where we're continuing our overview of generating charts for your AdSense reporting with Google Chart Tools. Today we’ll examine how to generate two other types of charts: a table chart and a geo chart.
The third chart requested by our CEO is a table chart. The table chart will contain the number of ad requests, the number of matched ad requests, and the number of individual ad impressions broken down by ad client ID.
Our request will have these parameters:
And the result will be similar to:
result = { "kind": "adsense#report", "totalMatchedRows": "4", "headers": [ {...} ], "rows": [ ["ca-afdo-pub-1234567890123456", "59", "55", "232"], ... ["partner-mb-pub-1234567890123456", "1", "0", "0"] ], "totals": ["", "278", "264", "825"], "averages": ["", "69", "66", "206"] }
As usual, let’s create a DataTable and a DataView to perform transformations on columns:
var data = new google.visualization.arrayToDataTable([['Ad client id', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS']] .concat(resp.rows)); var view = new google.visualization.DataView(data); view.setColumns([ 0, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 1))}, type:'number', label:'Ad requests'}, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 2))}, type:'number', label:'Matched ad requests'}, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 3))}, type:'number', label:'Individual ad impressions'} ]);
Finally, let’s draw the table chart. Note that there is no title for a table chart: if you need one, you’ll have to add it in a different element.
var tableWrapper = new google.visualization.ChartWrapper({ chartType: 'Table', dataTable: view, containerId: 'vis_div' }); tableWrapper.draw();
The table chart for our CEO is ready, and it can be sorted and paged.
Check the live example and the source code for today!
Finally, the last chart requested from our CEO: a geo chart. The geo chart will show the number of page views for the year broken down by country name.
result = { "kind": "adsense#report", "totalMatchedRows": "9", "headers": [ {...} ], "rows": [ ["Canada", "1"], ... ["United States", "52"] ], "totals": ["", "241"], "averages": ["", "26"], }
DataTable and DataView creation step:
var data = new google.visualization.arrayToDataTable( [['Country', 'Page Views']].concat(resp.rows)); var view = new google.visualization.DataView(data); view.setColumns([ 0, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 1))}, type:'number', label:'Page views'} ]);
Now we can draw the geo chart. For the geo chart there is no title:
var geoChartWrapper = new google.visualization.ChartWrapper({ chartType: 'GeoChart', dataTable: view, containerId: 'vis_div' }); geoChartWrapper.draw();
Et voilà! We have a map of the world with colors and values assigned to specific countries representing the page views from the countries for the current year.
Check the live example and the source code for today.
Eager to try to see what you can do combining these two powerful Google APIs?
You can start immediately using our Google API Explorer and our Google Visualization PlayGround. You can use the Explorer to query our AdSense Management API, and then use the results inside the code on the Visualization PlayGround to generate a chart.
In the next and final part of this series, we will see how to assemble multiple charts into dashboards and enrich them with interactive controls to manipulate the data they display.
Meanwhile, feel free to post any questions related to Google Chart Tools in Google Visualization API forum, or visit our AdSense Management API forum to ask general questions.
It's Chart Tools week here on the blog, and so we'll be showing you in a 4-part series how to easily generate charts for your AdSense reporting using Google Chart Tools. In today’s second post we’ll examine how to generate another type of chart: a column chart.
The second item required by our CEO is a column chart. The column chart will show the number of page views, ad requests, matched ad requests and individual ad impressions for each month of the current year.
Our request becomes:
Now the result will be similar to:
result = { "kind": "adsense#report", "totalMatchedRows": "9", "headers": [ {...{ ], "rows": [ ["2011-01", "28", "46", "41", "165"], ... ["2011-11", "2", "3", "3", "3"] ], "totals": ["", "241", "278", "264", "825"], "averages": ["", "26", "30", "29", "91"] }
We create the DataTable object, adding the columns for our dimensions:
// Create the data table. var data = new google.visualization.arrayToDataTable( [['Month', 'PAGE_VIEWS', 'AD_REQUESTS', 'MATCHED_AD_REQUESTS', 'INDIVIDUAL_AD_IMPRESSIONS']].concat(result.rows));
Once again we use a DataView to convert the string values to numbers:
var view = new google.visualization.DataView(data); view.setColumns([ 0, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 1))}, type:'number', label:'Page views'}, ... {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 4))}, type:'number', label:'Individual ad impressions'} ]);
And finally, let’s create a wrapper for the column chart and draw it:
var columnChartWrapper = new google.visualization.ChartWrapper({ chartType: 'ColumnChart', dataTable: view, options: {'title': 'Performances - Year 2011'}, containerId: 'vis_div' }); columnChartWrapper.draw();
Another piece is done: a column chart of our performances that is also displaying tips when hovering over bars. Check the live example and the source code for today!
You can start immediately by using our Google API Explorer and our Google Visualization PlayGround. You can use the Explorer to query our Management API, and then use the results inside the code on the Visualization PlayGround to generate a chart.
Stay tuned for our next post this week, where we’ll show you how to generate other two charts, a table chart and a geo chart.
If you have any questions related to the AdSense Management API, come to our forum; alternatively, visit the Google Visualization API forum if you're looking for support on Chart Tools.
result = { "kind": "adsense#report", "totalMatchedRows": "9", "headers": [ {...} ], "rows": [ ["2011-01", "46"], ... ["2011-11", "3"] ], "totals": ["", "278"], "averages": ["", "30"] }
// Create the data table. var data = new google.visualization.arrayToDataTable( [['Month', 'AD_REQUESTS']].concat(result.rows));
AD_REQUESTS
var view = new google.visualization.DataView(data); view.setColumns([ 0, {calc:function(dataTable, rowNum) {return parseInt(dataTable.getValue( rowNum, 1))}, type:'number', label:'Ad requests'} ]);
containerId
var lineChartWrapper = new google.visualization.ChartWrapper({ chartType: 'LineChart', dataTable: view, options: {'title': 'Ad requests trend - Year 2011'}, containerId: 'vis_div' }); lineChartWrapper.draw();