TeeChart for Javascript

User Guide

Rev. 1.0, Dec 2014

Introduction

This document explains in detail how to create charts and graphs using the TeeChart for Javascript library.

Adding charts to your web pages or applications is fun and easy, see the one-minute Starting Guide , play with the Online Demos  or discover the full TeeChart API Reference .

Compared with other programming environments (Java, .NET, Delphi VCL / FireMonkey, etc), the TeeChart Javascript api implements an essential subset of features in order to minimize both the script size and coding complexity.

Current script sizes are 64KB  (minified) and 13KB (gzipped)

The Tee namespace

Full code is wrapped around a single “ Tee ” identifier (namespace) to avoid cluttering the browser Window global space.  Several “classes” in an object-oriented manner exist Inside the Tee namespace, being Tee.Chart  the main class that defines a chart.

The Canvas

Charts are displayed by default using HTML5 Canvas  elements. The main class “Tee.Chart” should be initialized passing the <canvas> element or its id as string:

<canvas id="canvas1" width="300" height="200"></canvas>

Using the canvas id:

var Chart1=new Tee.Chart("canvas1");

Or using the element:

var Chart1=new Tee.Chart(document.getElementById("canvas1"));

Hidden charts can be created without passing any canvas parameter:


var Chart1=new Tee.Chart();

Drawing

Charts are rendered to canvas when calling the draw method:

Chart1.draw();

Bounds and position

The default xy position of charts inside canvas is 0,0  (left-top corner), and the default size is the same as the associated canvas.

You can override them by changing the chart bounds property:

Chart1.bounds.x=50;
Chart1.bounds.y=20;

Chart1.bounds.width=200;

Chart1.bounds.height=150;

Format

Most objects (like Series, Annotations and chart sub-objects) include a “format” property to

group all visual attributes in a common place.

The Format  class provides the following properties:

fill :  A color in css string format, for example:  #123456,  rgb(255,0,0),   rgba(0,255,0,0.5),  “blue”

Chart1.panel.format.fill = “blue”;

round :  Amount in pixels of roundness of rectangle corners (x: horizontal, y: vertical)

Chart1.panel.format.round = { x:10, y:10 }

Chart1.legend.format.round.y = 5;

transparency :  Amount of semi-glass effect, from 0 to 1. (default is zero)

Chart1.legend.format.transparency = 0.5;

shadow : Properties to control drop-shadow visibility behind filled shapes or stroked lines.

   var s = Chart1.panel.format.shadow;

   s.visible = true;

   s.width = 4;         // can be negative for left-side shadow

   s.height = 4;     // can be negative for top-side shadow

   s.blur = 5;

   s.color = “silver”;

gradient:   Attributes to fill shapes using a gradient of colors:

  var g = Chart1.panel.format.gradient;

  g.visible = true;

  g.colors = [ “red”, “yellow”, “green” ];   // array of colors

  g.stops = [ 0, 0.1, 1 ];   //  percentages from 0 to 1 for each color (default is null, automatic)

  // “bottomtop”, “leftright”, “rightleft”, “radial”, “diagonalup”, “diagonaldown”

  g.direction = “topbottom”;  

stroke: Attributes used to draw lines and outlines around filled shapes:

    var s = Chart1.panel.format.stroke;

    s.fill = “black”;

    s.size = 4;              // line thickness

    s.join = “round”;     // segment joins (“round”, “miter”, “bevel” )

    s.cap = “square”;    // ending line terminators (“square”, “butt”, “round” )

    s.dash = [ 5,10 ];    // dot-dash... array of pixels (default is null to draw solid lines)

    s.gradient.visible = true;    // gradient object with colors, direction, etc

font :  Properties to display text:

    var f = Chart1.title.format.font;

   f.style = “22px Verdana”;     // or: “bold italic 14px Tahoma”, etc, etc

   f.fill = “blue”;

   f.shadow.visible = true;     // text drop-shadow

   f.stroke.fill = “white”;         // draws an outline around text

   f.gradient.visible = true;    // fills text with gradient instead of using font.fill

    f.textAlign = “center”;     // horizontal alignment: “start”, “end”, “left”, “center”, “right”

   // vertical alignment: “top”, “middle”, “bottom”, “alphabetic”, “hanging”, “ideographic”

    f.baseLine = “top”;    

Background

The chart background appearance is controlled by the “panel” sub-object:

Chart1.panel.transparent = false;

The panel property includes a format subproperty to control background’s appearance:

Chart1.panel.format.gradient.visible = true;

Chart1.panel.format.shadow.color=”black”;

… etc

Title and Footer

These two chart properties are used to display text at chart top and bottom sides:

Chart1.title.text = “Hello”;

Chart1.footer.text = “World”;

Multiple-line text is done by adding “\n” line-feed delimiters:

Chart1.title.text = “Hello \n World”;

Title and Footer are Annotation-derived objects, and such they inherit the “format” sub-properties:

Chart1.title.visible = true;

Chart1.title.transparent = false;

Chart1.title.format.gradient.visible = true;

Chart1.title.format.round.x=20;

Adding data to series

Data is added to a chart using “ Series ” objects.

Multiple series can exist in the same chart. Each series can be of a different type ( line , area , bar , pie , etc) so you can mix several styles altogether.

Direct data:

The simplest way to add data to a chart is by passing an array of values at chart construction time:

var Chart1=new Tee.Chart("canvas1", [ 5,6,2,9,1] );

This creates a new series object of type Tee.Bar by default, and assigns the array to series.data.values property.

Multiple series are created when passing a multi-dimensional array:

var Chart1=new Tee.Chart("canvas1", [ [ 5,6,2,9,1], [ 8,4,3,7,5] ] );

The default series style Tee.Bar can be changed passing a type parameter:

var Chart1=new Tee.Chart("canvas1", [ [ 5,6,2,9,1], [ 8,4,3,7,5] ] , Tee.Area);

Creating series:

Series are manually added into a chart using the addSeries method:

var bar =Chart1.addSeries(new Tee.Bar());

Series have a default “title” string property that is used at chart legend.

When series are added to a chart, title is assigned to “Series” plus the series index in the Chart1.series.items  array (“Series1”, “Series2” and so on).

You can override the default title:

bar.title = “My Data”;

By default series are empty, they contain no data.

For testing purposes its handy to add random values, for example:

Chart1.addSeries(new Tee.Line()).addRandom(1000);   // Thousand random points

Data can be specified inline when creating the series:

Chart1.addSeries(new Tee.Pie( [ 10, 20, 30, 40 ] ));

All data is stored under the series “data” property arrays.

You can access and modify data directly:

var a = new Tee.Area();

Chart1.addSeries( a );

a.data.values =  [ 10, 20, 30, 40 ];

Each series point has an associated text label. By default labels are empty, you can modify them using the data.labels property:

a.data.labels =  [ “a”, “b”, “c”, “d” ];

Some series allow specifying point positions or other point parameters.

For example, Line  and PointXY  series can optionally display each line segment or point at a specific “X” axis coordinate:

var p = new Tee.PointXY();

p.data.values = [5, 7, 9];

p.data.x = [0.23, 14, 16];

Chart1.addSeries(p);

Other series like   Bubble  have a “data.radius” array, and Candle  series have data.open, data.close, data.high and data.low arrays.

Adding data from other sources

Several helper functions are provided in a separate script (teechart-table.js) to import data from different sources (see the online demos for details), for example:

From a textarea html element:

Chart1.addSeries(new Tee.Bar(document.getElementById("data")) );

<textarea id="data" rows="20" cols="20" wrap="off">
 7,Apples
 4
 3,Oranges
 9
 1,Banana
 6,Kiwis
 2</textarea>

From a table html element:

Chart1.fromTable('table1', Tee.Bar, true, 0,0);

<table id=”table1”>...</table>

From a text file URL:

// Warning: data file url should be at “same domain origin”

Chart1.addSeries(new Tee.Bar(“http://myweb.com/mydata.txt”));

From another series in same or different chart:

// Simply assign the “data” property from one series to another:

Chart1.series.items[0].data = Chart2.series.items[3].data;

From xml formatted text:

 var b=Chart1.addSeries(new Tee.Bar());
 b.loadXML(document.getElementById("xml"));

...
<textarea id="xml" rows="10" cols="60" "wrap="off">
<series name="Friends" color="Blue" metric="Quantity">
 <point name="Facebook" value="123"/>
 <point name="Twitter" value="456"/>
 <point name="Google+" value="789"/>
</series>
</textarea>

From JSON formatted text:

var b=Chart1.addSeries(new Tee.Bar());
b.loadJSON(document.getElementById("json"));

The Legend

The indicator where series names and series points are displayed is called the legend.

Several properties can be used to customize the legend behaviour and appearance.

Chart1.legend.visible = true;

Chart1.legend.transparent = false;

Chart1.legend.format.fill = “yellow”;

Legend position and orientation:

Chart1.legend.position = “left”;   // “top”, “bottom”, “right”

Chart1.legend.inverted = false;     // draws items in normal order

Select what to display at legend:

Chart1.legend.legendStyle = “values”;    // “auto”, “series”, “values”

Chart1.legend.textStyle = “percentlabel”;     // show point value as percent, and point text label

Font and formatting:

Chart1.legend.format.font.style = “20px Arial”;

Margins to chart top and chart axes:

// distance from chart edge, percentage from 0 to 100 ( 0 means automatic )

Chart1.legend.align = 0;  

// distance from legend to axes

Chart1.legend.padding = 5;    //  in pixels

Title text on top of items:

Chart1.legend.title.text = “My Legend”;

Chart1.legend.title.visible = true;

Symbols next to legend items:

Chart1.legend.symbol.visible = true;

Chart1.legend.symbol.width = 20;

Chart1.legend.symbol.format.shadow.width = 5;

Other legend properties:

Chart1.legend.fontColor = true;   // each item text is painted using its point or series color

Chart1.dividing.fill = “blue”;    // draws lines between legend items

Axes

Most Series data are displayed using axes to convert from data values to canvas pixel coordinates.  Some series like Pie and Donut do not use axes.

There exist four default axes inside a chart:  left, top, right and bottom.

var a = Chart1.axes.left;

Each series has two properties that control which horizontal and vertical axes are used.

By default, the horizontal axis is “bottom”, and the vertical axis is “left”.

Chart1.series.items[0].horizAxis = “top”;

Chart1.getSeries(1).vertAxis = “right”;

Series can also display using both axes:

Chart1.series.items[2].horizAxis = “both”;

Axis visibility is controlled globally by the Chart1.axes.visible property, and individually using the axis visible:

Chart1.axes.visible = true;

Chart1.axes.bottom.visible = true;

Scales are automatically controlled by default. Each axis calculates its minimum and maximum values based on its associated series values and visual properties.

You can override axis automatic scales and set them manually:

var a = Chart1.axes.left;

a.automatic = false;

a.minimum = 50;

a.maximum = 200;

The above code is equivalent to:

Chart1.axes.left.setMinMax( 50, 200 );

Logarithmic scales

Axes scales are linear by default. The log property determines the axis to use natural logarithm scaling instead of linear:

Chart1.axes.left.log = true;

Axis Labelling

Each axis automatically calculates the “best” distance from labels, using labels formatting properties like font.size.  Custom labels can be controlled changing the axis increment property:

Chart1.axes.bottom.increment = 100;    // one label at each 100 values in axis scale.

Increment is zero by default, meaning automatic calculation.

Labels can display series values or series point labels. This is controlled with the labelStyle property:

// options are:  “auto”, “none”, “value”, “mark”, “text”, “x”

Chart1.axes.left.labels.labelStyle = “text”;

When series contain date-time values, labels are formatted according to dateFormat property using Steven Levithan <stevenlevithan.com> date.format.js  library.

Chart1.series.items[0].data.x = [ new Date() ];

Chart1.axes.bottom.labels.dateFormat = “shortDate”;

Other properties that control labels:

Chart1.axes.left.labels.alternate = true;  // double quantity of labels

Chart1.axes.right.labels.visible = false;  // show or hide labels

Chart1.axes.left.labels.decimals = 3;    // output numbers with up to 3 fixed decimals

Chart1.axes.bottom.labels.rotation = 90;    // 90 degree rotation

Axis Grids

The axis grid property includes a format to draw grid lines that go across chart axes space.

Chart1.axes.left.grid.visible = true;

When grid fill color is not empty, grids are filled alternatively as “bands”:

Chart1.axes.left.grid.format.fill = “red”;

Grid lines format is controlled by stroke property:

Chart1.axes.left.grid.format.stroke.size = 5;

Default grid lines are solid lines. The lineDash property displays dash-dot grids:

Chart1.axes.left.grid.lineDash = true;

On browsers that natively support canvas dash strokes, the above code is equivalent to:

Chart1.axes.left.grid.format.stroke.dash = [10,5];    // see “dash” stroke property

Axis Ticks

Axis include ticks an innerTicks properties of type “Ticks”, that have a stroke property.

Ticks are drawn from labels to axis. Inner ticks display from axis towards inside.

Chart1.axes.bottom.innerTicks.visible = true;

Chart1.axes.left.ticks.length = 9;

Chart1.axes.top.ticks.stroke.fill = “blue”;

Minor Ticks

From tick to tick, the minorTicks axis property can be used to display small sub-ticks:

Chart1.axes.left.minorTicks.visible = true;

Chart1.axes.left.minorTicks.length = 2;

Chart1.axes.left.minorTicks.count = 5;

Chart1.axes.left.minorTicks.stroke.fill = “green”;

Axis Title

Close to an axis, the title property is used to display text that identifies the axis:

Chart1.axes.bottom.title.text = “Quantity”;

Chart1.axes.bottom.title.text.format.font.fill = “red”;

Axis positioning

Size and position of axes is automatic by default.

The axis startPos and endPos properties control the pixel coordinate of axes.

Axes Wall

The rectangular space where axes are painted is called “the back wall”.

Formatting is provided using the walls.back property:

Chart1.walls.back.visible = true;

Chart1.walls.back.transparent = false;

Chart1.walls.back.format.gradient.visible = true;

Series

Inheriting from a common Series class, several charting styles are provided, each as a different object class with its own properties and methods.

  1. Line
  2. Bar  / Horizontal Bar
  3. Area / Horizontal Area
  4. PointXY (scatter)
  5. Pie
  6. Donut
  7. Bubble
  8. Candle (financial OHLC)

Series Marks

The marks property displays text annotations near series points:

var s = new Tee.Bar();

s.marks.visible = true;

s.marks.style = “percent”;

Series and Colors

Charts have a palette property (an array [ ] of colors in string format).

This palette is used by series to paint its points, and by chart legend to display series items symbols.

Chart1.palette = [ “red”, “blue”, “green”, “yellow” ];

Colors in the palette are reused in a circular way when more series or more points in a series exist than the size of the palette.

Series also contain a palette of colors to override the chart palette. By default is a “null” empty array so they share the chart palette.

Zoom and Scroll

Charts can be zoomed and scrolled by manual code or mouse / touch events.

Default behaviour is to drag the right mouse button inside axes to scroll, and drag a rectangle using the left mouse button to zoom / unzoom (zoom dragging to bottom-right direction, and unzoom dragging to left-top direction).

This can be overridden using the chart zoom and scroll properties:

Chart1.zoom.enabled = true;

Chart1.zoom.mouseButton = 0;    // 0=left button, 1=middle, 2=right button

Chart1.zoom.stroke.fill = “yellow”;

Chart1.scroll.enabled = true;

Chart1.scroll.mouseButton = 2;

Chart1.scroll.direction = “horizontal”;   // can be: “vertical” or “both”

The chart onzoom event is triggered when the user releases the mouse button after the chart is zoomed.

The chart onscroll event is triggered while the user is scrolling the chart by dragging it.

Exporting a Chart

To obtain a PNG or JPEG image from a chart, you can use the canvas toDataURL method, or the included toImage function:

Chart1.toImage( “img” );    // fills <img id=”img”> element with chart as PNG image.

Chart1.toImage( “img” , “jpg”, 90 );    // fills image with a jpeg image with 90% compression

Charting Tools

Some features are implemented as a “tool” objects.  These objects can be added to a chart tools array property to activate them.

Annotations

Custom text can be displayed at any chart position using annotation tools:

Chart1.tools.add( new Tee.Annotation( Chart1, “Hello”, 50, 50 ) );

The annotation object has a format, text and position properties.

Annotations can also act as buttons when using the onclick event:

var  b1=new Tee.Annotation(Chart1, “button 1”, 100, 100);

b1.cursor="pointer";

b1.onclick=function(button,x,y) { alert("Clicked button 1"); }

Chart1.tools.add( b1 );

Tooltips

This tool displays series data when moving the mouse over series data point.

var  tip=new Tee.ToolTip(Chart1);

tip.format.font.style="16px Tahoma";

Chart1.tools.add(tip);

The ToolTip tool provides onshow, onhide and ongettext events.

Cursors

Draggable cursor lines are implemented as a tool object:

  var t=new Tee.CursorTool(Chart1);

  t.format.stroke.size=2;

  t.format.stroke.fill="#BB0000";

  Chart1.tools.add(t);

The cursor tool includes a direction property (to display cursor as an horizontal line, vertical or both) and an onchange event that is triggered when the cursor is dragged.

Dragging Points

The DragTool implements mouse / touch point dragging.

  Chart1.tools.add(new Tee.DragTool(Chart1));

Includes onchanging and onchanged events.

The target property determines which series and which series point index is being dragged.

Slider

A generic slider control that can be used inside a chart to change any value.

 var slider=new Tee.Slider(Chart1);

  slider.min=1;

  slider.max=100;

  slider.position=10;

  slider.thumbSize=12;

  slider.horizontal=true;

  slider.bounds.x=50;

  slider.bounds.y=10;

  slider.bounds.width=150;

  slider.bounds.height=20;

  slider.onChanging=function(slider,value) {

    Chart1.title.format.font.style = value.toFixed(0) + “ Verdana”;

    return value;

  }

  Chart1.tools.add(slider);

Scroller

The scroller tool displays a simplified view of another chart and allows scrolling it.

Please refer to this demo  for a complete example.

Series Animations

Simple animations performed by changing axis scales or rotating transformations:

  var a=new Tee.SeriesAnimation(Chart1);

  a.duration=500; // milliseconds

  Chart1.tools.add(a);

The animate method to start the animation can be called for example from an html button:

<BUTTON type="button" onclick="Chart1.tools.items[0].animate();">Animate</BUTTON>

Acknowledgements

The following are libraries and code snippets that have been used to develop TeeChart for Javascript:

date.format.js  by Steven Levithan

Used by chart axes to format date-time string labels from series data. (See axis dateFormat property).

splines  Copyright 2010 by Robin W. Spencer

Custom modified code to draw smooth curves between series points (Line, Area, etc).

JQuery.js , JSON  and Three.js  are technologies used in TeeChart online demos that are optional (not required by TeeChart).