[go: up one dir, main page]

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.

Defining week and month view

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.

The function setMonthView shows:

  • how to set the view window of the chart so that the values on the X axis (the dates) goes from 0 to the last day of the current month

  • how to add the required text to points on the X axis

  • how to visualize the subset of columns that we want in the month view.

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.

Handling events

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.

Job done!

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!

Some more thoughts on the User Experience

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.

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.

The goal

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:

  • The chart is initially shown in a month view: standard columns are shown for the days of the current month up to the current day. For the current and future days we draw the columns with a different visualization style, to visually outline the uncertainty of the data measurement. On the X axis we show 4 or 5 titles, for day 1, 8, 15, 22 and 29 (except for non leap year February). The title is the day of the month.

  • By clicking one of the columns, the user can zoom the chart to a week view. In the week view we show the values over the week centered on the day selected by the user: 7 columns are visualized, and for each data point we show the title on the X axis. We also add two other columns to the data visualization in order to supply more detailed information:

  • Finally, we add to the visualization a Zoom Out button to allow the user to go back to the month view. The Zoom Out button will disappear when the user zooms all the way out.

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.

Getting to the goal: fetching the data

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.

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.

Formatting the data: using roles

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:

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.

Formatting the data: the content

After defining the columns, we can add rows of data to our DataTable. To do this, we need to keep the following into account:

  • The AdSense Management API will return a result for a day only if there is a nonzero value for that day. In other words, if one day we had zero views, the API will not return a result for that day. This also means that we will not get results for days in the future.

  • We want to make the certainty of a data point visible, so that we have a different visualization for measures that are certain and measures that are in progress or not started.

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.

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.

Enough for today!

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.

Interaction with data

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:

  • combine the data retrieved from the AdSense Management API into one single table
  • create the charts
  • add 1 control, a Number Range Filter for ad requests
  • create a view on top of the data table
  • create a Dashboard object and feed it with the view

Create the DataTable

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:

start date:2011-01-01
end date:2011-12-31
dimensions:MONTH
metrics:PAGE_VIEWS, AD_REQUESTS, MATCHED_AD_REQUESTS, INDIVIDUAL_AD_IMPRESSIONS
filters:(none)

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));

Create the charts

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:

  • For each chart in a dashboard, we use the view option to select which columns are relevant for the chart (remember, all the data for the two charts is in the same table now)
  • We don’t draw the charts now, we’ll draw the entire dashboard later

Time to create the control!

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.

Create the DataView

Remember that we need a DataView to convert our string field to numeric fields:

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'},
]);

Create the dashboard

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:

<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!

Mission Accomplished!

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.

Table 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:

start date:2011-01-01
end date:2011-12-31
dimensions:AD_CLIENT_ID
metrics:AD_REQUESTS, MATCHED_AD_REQUESTS, INDIVIDUAL_AD_IMPRESSIONS
filters:(none)

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!

Geo chart

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.

Our request will have these parameters:

start date:2011-01-01
end date:2011-12-31
dimensions:COUNTRY_NAME
metrics:PAGE_VIEWS
filters:(none)

And the result will be similar to:

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.

Time to play!

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.

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:

start date:2011-01-01
end date:2011-12-31
dimensions:MONTH
metrics:PAGE_VIEWS, AD_REQUESTS, MATCHED_AD_REQUESTS, INDIVIDUAL_AD_IMPRESSIONS
filters:(none)

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!

Time to play!

Eager to try to see what you can do combining these two powerful Google APIs?

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.


It’s Monday morning, and you’re sitting in front of your computer, ready for a relaxed start of the week. But wait!

You’ve received an email from your CEO. He wants you to add AdSense reporting to his dashboard, and he wants to see the following:
  • a line chart showing the number of ad requests for the current year, broken down by month
  • a column chart showing the number of page views, ad requests, matched ad requests and individual ad impressions for the current year, broken down by month
  • a table showing the number of ad requests, matched ad requests and individual ad impressions for the current year, broken down by ad client id
  • a geo chart showing the number of page views for the current year broken down by country
He also requires the ability to interact with data: he wants to refine the visualization of the line and column charts filtering by lowest and highest number of ad requests shown in the charts.

It might look like a week of hard work is coming, but don’t worry! It’s Chart Tools week here on the AdSense Management API blog, and we’re going to show you how to easily and rapidly create the dashboard using the Google AdSense Management API and the Google Chart Tools. In the first part of this series, we’ll examine how to generate a line chart.

Background


You can access the AdSense Management API from different programming languages using the appropriate Google APIs Client. Check our documentation for AdSense Management API specific information.

The Google Chart Tools API are accessible using Javascript, check this ‘Hello Charts’ example for a quick start lesson on the API.

Line chart


The CEO wants a line chart showing the number of ad requests for the current year, broken down by month.

We will send a request to the AdSense Management API with the following parameters:
start date:2011-01-01
end date:2011-12-31
dimensions:MONTH
metrics:AD_REQUESTS

And the result will be a json array similar to the following:
result = {
  "kind": "adsense#report",
  "totalMatchedRows": "9",
  "headers": [ {...} ],
  "rows": [
    ["2011-01", "46"],
    ...
    ["2011-11", "3"]
  ],
  "totals": ["", "278"],
  "averages": ["", "30"]
}
To use the Chart API we first need to create a DataTable object representing the result of our request:
// Create the data table.
var data = new google.visualization.arrayToDataTable(
    [['Month', 'AD_REQUESTS']].concat(result.rows));
The AdSense Management API is returning the value for AD_REQUESTS as a string, but we need a numeric value for our charts. To achieve this, we are going to build a Data View on top of our Data Table and convert the string column to a number column:
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'}
]);
Our DataView will use the first column of the DataTable as it is, but will generate on the fly a second column composed of numeric values by calling a function of our choice that implements the conversion.

Finally we can draw the chart using a chart wrapper and passing our DataView to the wrapper. Make sure to define an element with id equal to the containerId parameter, as this is where the chart will be drawn.
var lineChartWrapper = new google.visualization.ChartWrapper({
  chartType: 'LineChart',
  dataTable: view,
  options: {'title': 'Ad requests trend - Year 2011'},
  containerId: 'vis_div'
});
lineChartWrapper.draw();
The line chart for the CEO is ready, and it’s also displaying tips when hovering over points. Check the live example and the source code for today!

Time to play!

Eager to try to see what you can do combining these two powerful Google APIs?

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.

In the next post of this series, we’ll look at how to generate a column chart.

Have questions in the meantime?