#

Jump to Table of Contents

# Charts

The Charts module provides a JavaScript API for visualizing data in a variety of formats across a browser test baseline. Based on device and browser capabilities, Charts leverages SVG, HTML Canvas and VML to render its graphical elements.

The Charts module features a `Chart` class that allows you to easily create a chart from a set of data. `Chart` extends `Widget` and includes configurable attributes that enable you to customize a Chart. Currently, the `Chart` widget can be used to create different variations and combinations of line, marker, area, spline, column, bar and pie charts.

## Getting Started

To include the source files for Charts and its dependencies, first load the YUI seed file if you haven't already loaded it.

    <script src="http://yui.yahooapis.com/3.10.3/build/yui/yui-min.js"></script>

Next, create a new YUI instance for your application and populate it with the modules you need by specifying them as arguments to the `YUI().use()` method. YUI will automatically load any dependencies required by the modules you specify.

    <script>
    // Create a new YUI instance and populate it with the required modules.
    YUI().use('charts', function (Y) {
        // Charts is available and ready for use. Add implementation
        // code here.
    });
    </script>

For more information on creating YUI instances and on the `use()` method, see the documentation for the YUI Global Object.

## Using the charts widget

This section describes how to use the charts widget in further detail. It contains these subsections:

### Instantiating A Chart

All you need to instantiate a chart is

1. A div container to render the chart.
2. An array to provide data for the chart.

*NOTE: By default, the chart will size itself to the dimensions of its container div. Be sure to include a width and height as demonstrated below:

#### CSS

    #mychart {
        width: 600px;
        height: 400px;
    }

#### HTML

    <div id="mychart"></div>

#### JavaScript

    // Data for the chart
    var myDataValues = [
        {category:"5/1/2010", values:2000},
        {category:"5/2/2010", values:50},
        {category:"5/3/2010", values:400},
        {category:"5/4/2010", values:200},
        {category:"5/5/2010", values:5000}
    ];

    // Instantiate and render the chart
    var mychart = new Y.Chart({
        dataProvider: myDataValues,
        render: "#mychart"
    });

By default, `Chart` creates a graph with lines and markers. This can be changed through the `type` attribute. Available values are listed below:

Type | Description
--- | ---
`area` | Visualizes quantitative data with a fill between an axis and relevant data points.
`areaspline` | An Area Chart in which data points are connected by a curve.
`bar` | Visualizes bars positioned vertically along a category or time axis. The bars' lengths are proportional to the values they represent along a horizontal axis.
`column` | Visualizes bars positioned vertically along a category or time axis. The bars' lengths are proportional to the values they represent along a horizontal axis.
`combo` | Combination of line, marker and area chart. By default, there is no area fill. This is the default type for a `Chart`.
`combospline` | A combo chart in which the data points are connected by a curve.
`line` | Visualizes quantitative data on a graph by connecting relevant data points.
`markerseries` | Visualizes quantitative data by plotting relevant data points on a graph.
`pie` | A circular chart divided into wedges which represent data as a percentage of a whole.
`spline` | Visualizes quantitative data on a graph by connecting relevant data points with a curve.

### Chart Application

The `Chart` class acts as a facade for two underlying application classes:

CartesianChart
  An application used to render multiple series to a graph with x and y axes. Many series can be rendered in a CartesianChart.
PieChart
  An application used to render Pie Charts.

When `Chart` is instantiated, the `type` attribute determines which class instance will be returned. A value of `pie` will return an instance of `PieChart`. All other values will return an instance of `CartesianChart`. For the most part, this is a distinction that only occurs under the hood. As a developer, this can be viewed as a single API.

### Attributes

The `Chart` widget adds the following key attributes, in addition to the attributes provided by the base Widget class:

Property | Type | Description
--- | --- | ---
`axes` | `Object` | Axes to appear in the chart. This can be an object of axis instances or object literals used to construct the appropriate axes.
`categoryAxis` | `Axis` | Reference to the chart's category axis.
`categoryAxisName` | `String` | Indicates the key value used to identify a category axis in the `axes` hash. If not specified, the categoryKey attribute value will be used.
`categoryKey` | `String` | The key value used for the chart's category axis. The default value is category.
`categoryType` | `String` | Indicates whether to use a `CategoryAxis` or `TimeAxis` for the `Chart` instance's category axis. The default value is category.
`dataProvider` | `Array` | Array of data used to construct the chart.
`direction` | `String` | Direction of chart's category axis when there is no series collection specified. Charts can be horizontal or vertical. When the chart type is column, the chart is horizontal. When the chart type is bar, the chart is vertical.
`horizontalGridlines` | `Gridlines` | Reference to the horizontalGridlines for a cartesian chart.
`interactionType` | `String` | Indicates the the `Chart` instance will fire `marker` or `planar` events. The default value is marker.
`legend` | `Object` | Provides a legend for a `Chart`.
`seriesCollection` | `Array` | Collection of series to appear on the chart. This can be an array of Series instances or object literals used to construct the appropriate series.
`seriesKeys` | `Array` | A collection of keys that map to the series axes. If no keys are set, they will be generated automatically depending on the data structure passed into the chart.
`showAreaFill` | `Boolean` | Indicates whether or not an area is filled in a combo chart.
`showLines` | `Boolean` | Indicates whether to display lines in a combo chart.
`showMarkers` | `Boolean` | Indicates whether to display markers in a combo chart.
`stacked` | `Boolean` | Indicates whether or not the chart is stacked.
`styles` | `Object` | properties for the chart.
`tooltip` | `Object` | Reference to the default tooltip available for the chart.
`type` | `String` | Indicates the default series type for the chart. The default value is `combo`
`valueAxisName` | `String` | Indicates the key value used to identify the default value axis.
`verticalGridlines` | `Gridlines` | Reference to the verticalGridlines for a cartesian chart.

### The `dataProvider` Attribute

The only required attributes for instantiating a `Chart` instance are `dataProvider` and `render`. The `render` attribute can be included in the configuration argument or called explicitly after instantiation.

    mychart.render("#mychart");

The `Chart` widget requires an array for its source of data. The `Chart` widget will accept an array of object literals or arrays. When an array of arrays is received, the values in the first index will be used for the category axis and all subsequent indices will be used for the value axis/axes. When an array of object literals is received, all records with a key matching the `categoryKey` attribute will be used for the category axis with all other records used for the value axis/axes.

#### Multi-dimensional Array

    var myDataValues = [
        ["5/1/2010", "5/2/2010", "5/3/2010", "5/4/2010", "5/5/2010"],
        [2000, 50, 400, 200, 5000]
    ];

#### Object Literal Array

    var myDataValues = [
        {category:"5/1/2010", values:2000},
        {category:"5/2/2010", values:50},
        {category:"5/3/2010", values:400},
        {category:"5/4/2010", values:200},
        {category:"5/5/2010", values:5000}
    ];

The underlying structure of the `dataProvider` is an array of object literals. If a `Chart` receives a multi-dimensional array for its `dataProvider`, it will convert the array to an array of object literals.

### Using the `tooltip` Attribute

The `Chart` class comes with a built-in simple tooltip. This tooltip can be customized or disabled with the `tooltip` attribute which contains the following properties:

Property | Type | Description
--- | --- | ---
`hideEvent` | `String`/`Array` | Event that hides the tooltip. This allows you to specify which mouse event(s) hides the tooltip. You can also pass this an array of events and each event in the array will hide the tooltip. The default value is `mouseout`.
`markerEventHandler` | `Function` | Displays and hides a tooltip based on marker events.
`markerLabelFunction` | `Function` | Reference to the function used to format a marker event triggered tooltip's text. The markerLabelFunction has the following arguments: categoryItem An object containing the following: axis The axis that the category is bound to displayName The display name set to the category (defaults to key if not provided) key The key of the category value The value of the category valueItem An object containing the following: axis The axis that the item's series is bound to displayName The display name of the series (defaults to key if not provided) key The key for the series value The value for the series item itemIndex The index of the item within its series. series The series that the item belongs to seriesIndex The index of the series in the seriesCollection The method returns an `HTMLElement` which is written into the DOM using `appendChild`. If you override this method and choose to return an html string, you will also need to override the tooltip's `setTextFunction` method to accept an html string. *NOTE: Previous to 3.5.0, this method used `innerHTML`. The functionality was changed to prevent potential security vectors. If you have current implementations in which your custom `markerLabelFunction` is dependent on `innerHTML` to format your text. You will need to either change them to work with `appendChild` or update the tooltip's `setFunction` method to accept an html string.
    tooltip: {
        setTextFunction: function(textField, val) {
            textField.setHTML(val);
        }
    }
If you use such a strategy, please ensure your content is safe.
`node` | `HTMLElement` | Reference (read-only) to the actual dom node of the tooltip.
`planarEventHandler` | `Function` | Displays and hides a tooltip based on planar events.
`planarLabelFunction` | `Function` | Reference to the function used to format a planar event triggered tooltip's text. The `planarLabelFunction` has the following arguments: categoryAxis Reference to the categoryAxis of the chart. valueItems Array of objects for each series that has a data point in the coordinate plane of the event. Each object contains the following data: axis The value axis of the series. key The key for the series. value The value for the series item. displayName The display name of the series. (defaults to key if not provided) index The index of the item within its series. seriesArray Array of series instances for each value item. seriesIndex The index of the series in the `seriesCollection`. The method returns an `HTMLElement` which is written into the DOM using `appendChild`. If you override this method and choose to return an html string, you will also need to override the tooltip's `setTextFunction` method to accept an html string. *NOTE: Previous to 3.5.0, this method used `innerHTML`. The functionality was changed to prevent potential security vectors. If you have current implementations in which your custom `planarLabelFunction` is dependent on `innerHTML` to format your text. You will need to either change them to work with `appendChild` or update the tooltip's `setFunction` method to accept an html string.
    tooltip: {
        setTextFunction: function(textField, val) {
            textField.setHTML(val);
        }
    }
If you use such a strategy, please ensure your content is safe.
setTextFunction | `Function` | Method that writes content returned from `planarLabelFunction` or `markerLabelFunction` into the the tooltip node. has the following signature: label The `HTMLElement` that the content is to be added. val The content to be rendered into tooltip. This can be a `String` or `HTMLElement`. If an HTML string is used, it will be rendered as a string.
`show` | `Boolean` | Indicates whether to show a tooltip.
`showEvent` | `String` | Event that triggers the tooltip. This allows you to specify which mouse event will cause the tooltip to display. The default value is `mouseover`
`styles` | `Object` | Hash of CSS styles that are applied to the tooltip's node.

### Styling a `CartesianChart` with the `styles` Attribute

The `styles` attribute can be used to update the properties of different chart components in a `CartesianChart`.

Property | Type | Description
--- | --- | ---
`axes` | `Object` | An object containing references to the `styles` attribute for each `Axis` instance in the chart.
`graph` | `Object` | A reference to the `styles` attribute of the chart applications's `Graph`.
`series` | `Object` | An object containing references to the `styles` attribute for each `CartesianSeries` instance in the chart.

### Using the `axes` Attribute

The `axes` attribute allows you to specify axes to be used in the chart. The `axes` attribute contains a hash of either `Axis` instances or object literals containing information that the `Chart` will use to create axes. The most common use case is to use object literals. Below are the attributes available:

Property | Type | Description
--- | --- | ---
`alwaysShowZero` | `Boolean` | Ensures that zero appears on a `NumericAxis` when `minimum` and `maximum` are not explicitly set.
`keys` | `Array` | An array keys used to bind data from the `dataProvider` to the axis.
`labelFormat` | `Object` | Template for formatting labels. Used by `labelFunction` in `NumericAxis` and `TimeAxis` instances. For `TimeAxis` instances the `labelFormat` is an `STRFTime` string. For `NumericAxis` instances the `labelFormat` is an object literal containing the following properties: prefix thousandsSeparator decimalSeparator decimalPlaces suffix
`labelFunction` | `Function` | Function used to format axis labels for display. The return value is added to the `Axis` with `appendChild`. *NOTE: Previous to 3.5.0, this method used `innerHTML`. The functionality was changed to prevent potential security vectors. If you have current implementations in which your custom `labelFunction` is dependent on `innerHTML` to format your text. You will need to either change them to work with `appendChild` or update the Axis' `appendLabelFunction` method to accept an html string.
    appendLabelFunction: function(textField, val) {
        textField.innerHTML = val;
    }
If you use such a strategy, please ensure your content is safe.
`appendLabelFunction` | `Function` | Function used to add the output of the `labelFunction` to the `Axis` using `appendChild`. This attribute can be overridden as needed.
`title` | `String` | Optional attribute that allows for specification of an axis title. The value of this attribute is added to the `Axis` with `appendChild`. *NOTE: Previous to 3.5.0, this attribute was added to the DOM using `innerHTML`. The functionality was changed to prevent potential security vectors. If you have current implementations in which the value of the `title` attribute is dependent on `innerHTML` to format your text. You will need to either change the value to an HTMLElement that can be added with `appendChild` or update the Axis' `appendTitleFunction` method to accept an html string.
    appendTitleFunction: function(textField, val) {
        textField.innerHTML = val;
    }
If you use such a strategy, please ensure your content is safe.
`appendTitleFunction` | `Function` | Function used to add the `title` attribute to the `Axis` using `appendChild`. This attribute can be overridden as needed.
`maximum` | `Object` | The maximum value to display on an axis. (`TimeAxis` and `NumericAxis` only)
`minimum` | `Object` | The minimum value to display on an axis. (`TimeAxis` and `NumericAxis` only)
`position` | `String` | Position in relationship to the graph in which to place the axis. (top, right, bottom, left)
`roundingMethod` | `String` | Algorithm used for rounding units on a `NumericAxis` when `minimum` and `maximum` are not explicitly set.

### Referencing Series and Axis Instances

Sometimes you'll want to update an axis or a series after a chart has been instantiatied. This can be done with the `Chart`'s `getAxisByKey` and `getSeries` methods. The `getAxisByKey` method looks up and returns an `Axis` instance based on its a key reference.

#### Using `getAxisByKey`

    var leftAxis = mychart.getAxisByKey("values");
    leftAxis.set("styles", {label:{rotation:-45}});

The `getSeries` method will accept either an index or a key reference and return a series.

#### Using `getSeries` with a Key

    var mySeries = mychart.getSeries("category");
    mySeries.set("visible", false);

#### Using `getSeries` with an Index

    var mySeries = mychart.getSeries(0);
    mySeries.set("visible", false);

### Using the `legend` Attribute

The `legend` attribute allows you to define a legend for your `Chart` instance. The `legend` is an object containing the attributes necessary for defining and styling the legend. You must include the 'charts-legend' module if you want have legends in your chart.

    YUI().use('charts-legend', function (Y) {
        // Charts is available and ready for use. Add implementation
        // code here.
    });

To see how to create a chart with a legend, check out the example. Below is a list of the available attributes.

Property | Type | Description
--- | --- | ---
chart | `Chart` | Reference to the `Chart` instance.
direction | `String` | Indicates the direction in relation of the legend's layout. The `direction` of the legend is determined by its `position` value.
position | `String` | Indicates the position and direction of the legend. Possible values are `left`, `top`, `right` and `bottom`. Values of `left` and `right` values have a `direction` of `vertical`. Values of `top` and `bottom` values have a `direction` of `horizontal`.
width | `Number` | The width of the legend. Depending on the implementation of the ChartLegend, this value is `readOnly`. By default, the legend is included in the layout of the `Chart` that it references. Under this circumstance, `width` is always `readOnly`. When the legend is rendered in its own dom element, the `readOnly` status is determined by the direction of the legend. If the `position` is `left` or `right` or the `direction` is `vertical`, width is `readOnly`. If the position is `top` or `bottom` or the `direction` is `horizontal`, width can be explicitly set. If width is not explicitly set, the width will be determined by the width of the legend's parent element.
height | `Number` | The height of the legend. Depending on the implementation of the ChartLegend, this value is `readOnly`. By default, the legend is included in the layout of the `Chart` that it references. Under this circumstance, `height` is always `readOnly`. When the legend is rendered in its own dom element, the `readOnly` status is determined by the direction of the legend. If the `position` is `top` or `bottom` or the `direction` is `horizontal`, height is `readOnly`. If the position is `left` or `right` or the `direction` is `vertical`, height can be explicitly set. If height is not explicitly set, the height will be determined by the width of the legend's parent element.
x | `Number` | Indicates the x position of legend.
y | `Number` | Indicates the y position of legend.
styles | `Object` | Properties used to display and style the ChartLegend. This attribute is inherited from `Renderer`. Below are the default values: gap Distance, in pixels, between the `ChartLegend` instance and the chart's content. When `ChartLegend` is rendered within a `Chart` instance this value is applied. hAlign Defines the horizontal alignment of the `items` in a `ChartLegend` rendered in a horizontal direction. This value is applied when the instance's `position` is set to top or bottom. This attribute can be set to left, center or right. The default value is center. vAlign Defines the vertical alignment of the `items` in a `ChartLegend` rendered in vertical direction. This value is applied when the instance's `position` is set to left or right. The attribute can be set to top, middle or bottom. The default value is middle. item Set of style properties applied to the `items` of the `ChartLegend`. hSpacing Horizontal distance, in pixels, between legend `items`. vSpacing Vertical distance, in pixels, between legend `items`. label Properties for the text of an `item`. color Color of the text. The default values is "#808080". fontSize Font size for the text. The default value is "85%". marker Properties for the `item` markers. width Specifies the width of the markers. height Specifies the height of the markers. styles Properties for the `ChartLegend` background. fill Properties for the background fill. color Color for the fill. The default value is "#faf9f2". stroke Properties for the background stroke. color Color for the stroke. The default value is "#dad8c9". weight Weight of the stroke. The default values is 1.

## Known Issues

- Custom formatting for tooltip's and axis title and labels has been updated for 3.5.0 and higher to prevent potential security vectors. This may cause backward compatibility issues when upgrading from 3.4.x and below under the following circumstances:

  - If you have written a custom `labelFunction` for your axis that is dependent upon `innerHTML` for formatting, the current implementation will need to be changed so that it will work with `appendChild`. Alternatively, there is a newly created `appendLabelFunction` attribute that can be overridden to use `innerHTML`. More information can be found under the labelFunction section here.
  - If you are dependent on `innerHTML` to format the value of an Axis `title`, you will need to pass in an HTMLElement that can be added using `appendChild`. Alternatively, there is a newly created `appendTitleFunction` attribute that can be overridden to use `innerHTML`. More information can be found under the title section here.
  - If you are using the `tooltip` attribute's `markerLabelFunction` or `planarLabelFunction` to add custom formatting to a chart's tooltip. You will need to update it so that is not dependent on `innerHTML`. The Customize a Chart's Tooltip example has been updated to demonstrate the correct way to construct a custom tooltip function. Alternatively, there is a newly created `setTextFunction` property of the `tooltip` attribute that can be overridden to use `innerHTML`. More information can be found under the markerLabelFunction and planarLabelFunction sections here.

- Charts load slowly in android devices. Performance optimizations will need to be added in a future release.

- Planar interaction with chart types that do not include markers can be confusing. It is not readily apparent where to mouseover to display tooltips. This will be addressed in a future release.

- Default mouse interactions are not intuitive for touch devices. For example, tooltips show and hide on `mouseover` and `mouseout` events. Analysis needs to be done to determine the appropriate default events for touch devices. See the Using the `tooltip` Attribute section to see how to customize mouse events for the chart.