Search code examples
javascriptgoogle-analyticsgoogle-analytics-api

Multi-series Charts in Google Analytics Embed API


I am using the Embed API to create a "LINE" chart of sessions per-day, per-medium (ga:sessions, ga:date, ga:medium, respectively), but I can only succeed in creating a single series (sessions per day).

var chart = new gapi.analytics.googleCharts.DataChart({
  query : {
    "ids"        : view_id,
    "start-date" : "30daysAgo",
    "end-date"   : "yesterday",
    "dimensions" : "ga:date", // Works, but only produces single series
    // "dimensions" : "ga:date,ga:medium", - Doesn't work
    "metrics"    : "ga:sessions",
  },
  chart : {
    type : "LINE",
    container : "ga-chart",
    options : {
      width: "100%",
      title : title,
    }
  },
});
chart.execute();

Using the commented line above produces the error "All series on a given axis must be of the same data type".

How do I get a separate series for each value of ga:medium ("referral", "organic" and "(none)").


Solution

  • Using the commented line above produces the error "All series on a given axis must be of the same data type".

    Yeah, so this is the problem. Google Charts doesn't know what you want. On the one hand you say you want an x-axis with type date, and then you say you want an x-axis with values that are random strings (ga:medium).

    What you're asking for makes logical sense to you (and me) because you're asking for a timeline, but there's no way the Embed API can make this work for any two dimensions. Consider ga:medium,ga:browser, how would that look on a chart?

    So the short answer is you can't do what you're asking with the Embed API's gapi.analytics.googleCharts.DataChart component. It supports multiple metrics in queries (since metrics are always numeric), but not multiple dimensions of different datatypes.

    The long answer is that you can use the gapi.analytics.report.Data component and run the query yourself, get the results back, and then construct your own Google Chart instance after you've manipulated the data into the format you need it in to work.

    I hope that helps.