VegaChart

Overview

A VegaChart is one of the many possible visualizations that may be created using the Vega Visualization Grammar, which is a declarative language for creating, saving, and sharing interactive visualization designs. With Vega, you can describe the visual appearance and interactive behavior of a visualization in a JSON format, and generate web-based views using Canvas or SVG.

When drawing a VegaChart, you must include within the options a specification for how to build the chart in the Vega visualization grammar. A few examples of such specifications are included below, and several more examples can be found on the VegaChart Examples page.

Note: While the Google Charts VegaChart can draw any Vega chart that you can specify with a Vega JSON Specification (including everything in the Example Gallery), additional features that require calls to the Vega API are not yet available.

A Simple Example, the Bar Chart

Here is a simple example of a VegaChart that draws a Bar Chart. (See the original example, a detailed tutorial, and the Bar Chart in Vega chart editor.)

While this represents yet another way to produce a bar chart in Google Charts, we plan to integrate all of the features of the other Bar and Column charts into a new implementation based on this VegaChart.

In this example, note that the 'data' option is replaced with the following, which uses the 'datatable' provided by the draw call as the 'source' for another data object called 'table', and 'table' is used in the remainder of the Vega spec.

  'data': [{'name': 'table', 'source': 'datatable'}],

<html>
  <head>
    <script src='https://www.gstatic.com/charts/loader.js'></script>
    <script>
      google.charts.load('upcoming', {'packages': ['vegachart']}).then(drawChart);

      function drawChart() {
        const dataTable = new google.visualization.DataTable();
        dataTable.addColumn({type: 'string', 'id': 'category'});
        dataTable.addColumn({type: 'number', 'id': 'amount'});
        dataTable.addRows([
          ['A', 28],
          ['B', 55],
          ['C', 43],
          ['D', 91],
          ['E', 81],
          ['F', 53],
          ['G', 19],
          ['H', 87],
        ]);

        const options = {
          "vega": {
            "$schema": "https://vega.github.io/schema/vega/v4.json",
            "width": 500,
            "height": 200,
            "padding": 5,

            'data': [{'name': 'table', 'source': 'datatable'}],

            "signals": [
              {
                "name": "tooltip",
                "value": {},
                "on": [
                  {"events": "rect:mouseover", "update": "datum"},
                  {"events": "rect:mouseout",  "update": "{}"}
                ]
              }
            ],

            "scales": [
              {
                "name": "xscale",
                "type": "band",
                "domain": {"data": "table", "field": "category"},
                "range": "width",
                "padding": 0.05,
                "round": true
              },
              {
                "name": "yscale",
                "domain": {"data": "table", "field": "amount"},
                "nice": true,
                "range": "height"
              }
            ],

            "axes": [
              { "orient": "bottom", "scale": "xscale" },
              { "orient": "left", "scale": "yscale" }
            ],

            "marks": [
              {
                "type": "rect",
                "from": {"data":"table"},
                "encode": {
                  "enter": {
                    "x": {"scale": "xscale", "field": "category"},
                    "width": {"scale": "xscale", "band": 1},
                    "y": {"scale": "yscale", "field": "amount"},
                    "y2": {"scale": "yscale", "value": 0}
                  },
                  "update": {
                    "fill": {"value": "steelblue"}
                  },
                  "hover": {
                    "fill": {"value": "red"}
                  }
                }
              },
              {
                "type": "text",
                "encode": {
                  "enter": {
                    "align": {"value": "center"},
                    "baseline": {"value": "bottom"},
                    "fill": {"value": "#333"}
                  },
                  "update": {
                    "x": {"scale": "xscale", "signal": "tooltip.category", "band": 0.5},
                    "y": {"scale": "yscale", "signal": "tooltip.amount", "offset": -2},
                    "text": {"signal": "tooltip.amount"},
                    "fillOpacity": [
                      {"test": "datum === tooltip", "value": 0},
                      {"value": 1}
                    ]
                  }
                }
              }
            ]
          }
        };

        const chart = new google.visualization.VegaChart(document.getElementById('chart-div'));
        chart.draw(dataTable, options);
      }
    </script>
  </head>

  <body>
    <div id="chart-div" style="width: 700px; height: 250px;"></div>
  </body>

</html>

Loading

The google.charts.load package name is "vegachart".

google.charts.load("current", {packages: ["vegachart"]});

The visualization's class name is google.visualization.VegaChart.

var visualization = new google.visualization.VegaChart(container);

Data Format

Data can be passed to a VegaChart in a very similar way as for other Google Charts, using a DataTable (or DataView). The main difference is that rather than relying on the order of the columns to determine how they are used, VegaChart relies on the id of each column being the same as what is expected for the particular Vega visualization you have specified. For example, the following DataTable is created with columns that have ids for 'category' and 'amount', and the same ids are used within the 'vega' option to reference these columns.

With DataTable
        const dataTable = new google.visualization.DataTable();
        dataTable.addColumn({type: 'string', 'id': 'category'});
        dataTable.addColumn({type: 'number', 'id': 'amount'});
        dataTable.addRows([
          ['A', 28],
          ['B', 55],
          ['C', 43],
        ]);

        const options = {
          'vega': {
            ...
            // Here we create the Vega data object named 'datatable',
            // which will be passed in via the draw() call with a DataTable.
            'data': {'name': 'datatable'},

            'scales': [
              {
                'name': 'yscale',
                // Here is an example of how to use the 'amount' field from 'datatable'.
                'domain': {'data': 'datatable', 'field': 'amount'},
              }
            ]
          }
        };

        const chart = new google.visualization.VegaChart(
          document.getElementById('chart-div'));
        chart.draw(dataTable, options);
    
With Vega inlined data
        // A DataTable is required, but it may be empty.
        const dataTable = new google.visualization.DataTable();
        const options = {
          'vega': {
            // Here the data is specified inline in the Vega specification.
            "data": [
              {
               "name": "table",
                "values": [
                  {"category": "A", "amount": 28},
                  {"category": "B", "amount": 55},
                  {"category": "C", "amount": 43},
                ]
              }
            ],

            'scales': [
              {
                'name': 'yscale',
                // Here is how Vega normally uses the 'amount' field from 'table'.
                "domain": {"data": "table", "field": "category"},
              }
            ]
          }
        };

        const chart = new google.visualization.VegaChart(
          document.getElementById('chart-div'));
        chart.draw(dataTable, options);
    

However, only one such DataTable can be passed in to the VegaChart this way, whereas some Vega charts require more than one data table. We will address this limitation in a future release of Google Charts.

In the meantime, you can specify any additional data you need to use in the 'vega' 'data' option, either by inlining it or by loading it from a URL. Examples of both can be found below.

Configuration Options

Name
chartArea

An object with members to configure the placement and size of the chart area (where the chart itself is drawn, excluding axis and legends). Two formats are supported: a number, or a number followed by %. A simple number is a value in pixels; a number followed by % is a percentage. Example: chartArea:{left:20,top:0,width:'50%',height:'75%'}

Type: object
Default: null
chartArea.bottom

How far to draw the chart from the bottom border.

Type: number or string
Default: auto
chartArea.left

How far to draw the chart from the left border.

Type: number or string
Default: auto
chartArea.right

How far to draw the chart from the right border.

Type: number or string
Default: auto
chartArea.top

How far to draw the chart from the top border.

Type: number or string
Default: auto
chartArea.width

Chart area width.

Type: number or string
Default: auto
chartArea.height

Chart area height.

Type: number or string
Default: auto
height

Height of the chart, in pixels.

Type: number
Default: height of the containing element
width

Width of the chart, in pixels.

Type: number
Default: width of the containing element

Methods

Method
draw(data, options)

Draws the chart. The chart accepts further method calls only after the readyevent is fired. Extended description.

Return Type: none
getAction(actionID)

Returns the tooltip action object with the requested actionID.

Return Type: object
getBoundingBox(id)

Returns an object containing the left, top, width, and height of chart element id. The format for id isn't yet documented (they're the return values of event handlers), but here are some examples:

var cli = chart.getChartLayoutInterface();

Height of the chart area
cli.getBoundingBox('chartarea').height
Width of the third bar in the first series of a bar or column chart
cli.getBoundingBox('bar#0#2').width
Bounding box of the fifth wedge of a pie chart
cli.getBoundingBox('slice#4')
Bounding box of the chart data of a vertical (e.g., column) chart:
cli.getBoundingBox('vAxis#0#gridline')
Bounding box of the chart data of a horizontal (e.g., bar) chart:
cli.getBoundingBox('hAxis#0#gridline')

Values are relative to the container of the chart. Call this after the chart is drawn.

Return Type: object
getChartAreaBoundingBox()

Returns an object containing the left, top, width, and height of the chart content (i.e., excluding labels and legend):

var cli = chart.getChartLayoutInterface();

cli.getChartAreaBoundingBox().left
cli.getChartAreaBoundingBox().top
cli.getChartAreaBoundingBox().height
cli.getChartAreaBoundingBox().width

Values are relative to the container of the chart. Call this after the chart is drawn.

Return Type: object
getChartLayoutInterface()

Returns an object containing information about the onscreen placement of the chart and its elements.

The following methods can be called on the returned object:

  • getBoundingBox
  • getChartAreaBoundingBox
  • getHAxisValue
  • getVAxisValue
  • getXLocation
  • getYLocation

Call this after the chart is drawn.

Return Type: object
getHAxisValue(xPosition, optional_axis_index)

Returns the horizontal data value at xPosition, which is a pixel offset from the chart container's left edge. Can be negative.

Example: chart.getChartLayoutInterface().getHAxisValue(400).

Call this after the chart is drawn.

Return Type: number
getImageURI()

Returns the chart serialized as an image URI.

Call this after the chart is drawn.

See Printing PNG Charts.

Return Type: string
getSelection()

Returns an array of the selected chart entities. For this chart, only one entity can be selected at any given moment. Extended description .

Return Type: Array of selection elements
getVAxisValue(yPosition, optional_axis_index)

Returns the vertical data value at yPosition, which is a pixel offset down from the chart container's top edge. Can be negative.

Example: chart.getChartLayoutInterface().getVAxisValue(300).

Call this after the chart is drawn.

Return Type: number
getXLocation(dataValue, optional_axis_index)

Returns the pixel x-coordinate of dataValue relative to the left edge of the chart's container.

Example: chart.getChartLayoutInterface().getXLocation(400).

Call this after the chart is drawn.

Return Type: number
getYLocation(dataValue, optional_axis_index)

Returns the pixel y-coordinate of dataValue relative to the top edge of the chart's container.

Example: chart.getChartLayoutInterface().getYLocation(300).

Call this after the chart is drawn.

Return Type: number
removeAction(actionID)

Removes the tooltip action with the requested actionID from the chart.

Return Type: none
setAction(action)

Sets a tooltip action to be executed when the user clicks on the action text.

The setAction method takes an object as its action parameter. This object should specify 3 properties: id— the ID of the action being set, text —the text that should appear in the tooltip for the action, and action — the function that should be run when a user clicks on the action text.

Any and all tooltip actions should be set prior to calling the chart's draw() method. Extended description.

Return Type: none
setSelection()

Selects the specified chart entities. Cancels any previous selection. For this chart, only one entity can be selected at a time. Extended description .

Return Type: none
clearChart()

Clears the chart, and releases all of its allocated resources.

Return Type: none

Events

For more information on how to use these events, see Basic Interactivity, Handling Events, and Firing Events.

Name
animationfinish

Fired when transition animation is complete.

Properties: none
click

Fired when the user clicks inside the chart. Can be used to identify when the title, data elements, legend entries, axes, gridlines, or labels are clicked.

Properties: targetID
error

Fired when an error occurs when attempting to render the chart.

Properties: id, message
legendpagination

Fired when the user clicks legend pagination arrows. Passes back the current legend zero-based page index and the total number of pages.

Properties: currentPageIndex, totalPages
onmouseover

Fired when the user mouses over a visual entity. Passes back the row and column indices of the corresponding data table element.

Properties: row, column
onmouseout

Fired when the user mouses away from a visual entity. Passes back the row and column indices of the corresponding data table element.

Properties: row, column
ready

The chart is ready for external method calls. If you want to interact with the chart, and call methods after you draw it, you should set up a listener for this event before you call the draw method, and call them only after the event was fired.

Properties: none
select

Fired when the user clicks a visual entity. To learn what has been selected, call getSelection().

Properties: none

Data Policy

All code and data are processed and rendered in the browser. No data is sent to any server.