Graph2d is an interactive visualization chart to draw data in a 2D graph. You can freely move and zoom in the graph by dragging and scrolling in the window.
Graph2d uses HTML DOM and SVG for rendering. This allows for flexible customization using css styling.
The following code shows how to create a Graph2d and provide it with data. More examples can be found in the examples directory.
<!DOCTYPE HTML> <html> <head> <title>Graph2d or Basic Example</title> <style type="text/css"> body, html { font-family: sans-serif; } </style> <script src="../../dist/vis.js"></script> <link href="../../dist/vis-timeline-graph2d.min.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="visualization"></div> <script type="text/javascript"> var container = document.getElementById('visualization'); var items = [ {x: '2014-06-11', y: 10}, {x: '2014-06-12', y: 25}, {x: '2014-06-13', y: 30}, {x: '2014-06-14', y: 10}, {x: '2014-06-15', y: 15}, {x: '2014-06-16', y: 30} ]; var dataset = new vis.DataSet(items); var options = { start: '2014-06-10', end: '2014-06-18' }; var Graph2d = new vis.Graph2d(container, dataset, options); </script> </body> </html>
The result of the code above will be the basic example which is shown here.
The class name of the Graph2d is vis.Graph2d
. When
constructing a Graph2d, an HTML DOM container must be provided to
attach the graph to. Optionally, data an options can be provided. Data
is a vis DataSet
or an Array
, described in
section Data Format. Options is a
name-value map in the JSON format. The available options are described
in section Configuration Options.
Groups is a vis DataSet
containing groups. The available
options and the method of construction are described in section
Data Format.
var graph = new vis.Graph2d(container [, data] [, groups] [, options]);For backwards compatibility, groups and options can be interchanged.
Data, options and groups can be set or changed later on using the
functions
Graph2d.setItems(data)
,
Graph2d.setOptions(options)
and
Graph2d.setGroups(groups)
.
Graph2d can load data from an Array
, a
DataSet
(offering 2 way data binding), or a
DataView
(offering one way data binding). Objects are added
to this DataSet by using the add()
function.
Graph2d can be provided with two types of data:
var items = [ {x: '2014-06-13', y: 30, group: 0}, {x: '2014-06-14', y: 10, group: 0}, {x: '2014-06-15', y: 15, group: 1}, {x: '2014-06-16', y: 30, group: 1}, {x: '2014-06-17', y: 10, group: 1}, {x: '2014-06-18', y: 15, group: 1} ];
Name | Type | Required | Description |
---|---|---|---|
x | Date | yes | Location on the x-axis. |
y | Number | yes | Location on the y-axis. |
group | Number or string | no | The ID of the group this point belongs to. |
label | Object | no | A label object which will be displayed near to the item. A label object has one requirement - a content property. In addition you can set the xOffset, yOffset and className for further appearance customisations. |
end | Date | no | A location on the x-axis that when supplied will have the bar stretch to the end point and ignore the barChart.width property. |
Like the items, groups are regular JavaScript Arrays and Objects. Using
groups, items can be grouped together. Items are filtered per group, and
displayed as individual graphs. Groups can contain the properties
id
, content
, className
(optional)
and options
(optional).
Groups can be applied to a timeline using the method
setGroups
. A table with groups can be created like:
var groups = new vis.DataSet(); groups.add({ id: 1, content: 'Group 1', // Optional: a field 'visible' // Optional: a field 'className' // Optional: options }) groups.add({ // more groups... });
Groups can have the following properties:
Name | Type | Required | Description |
---|---|---|---|
id | String or Number | yes |
An id for the group. The group will display all items having a
property group which matches the id of the
group.
|
content | String | yes | The contents of the group. This can be plain text or html code. |
className | String | no | This field is optional. A className can be used to give groups an individual css style. |
style | String | no | This field is optional. A style can be used to give groups an individual css style, and any style tags specified in style will override the definition in the className style defined in css. |
options | Object | no | This field is optional. The options can be used to give a group a specific draw style. Any options that are colored green in the Configuration Options can be used as options here. |
visible | Boolean | no | This field is optional. If false, this group will not be drawn. By default it is true. |
setOptions
function.
var options = { width: '100%', height: '400px', style: 'surface' };The options colored in green can also be used as options for the groups. All options are optional.
Name | Type | Default | Description |
---|---|---|---|
defaultGroup | String | 'default' | This is the label for the default, ungrouped items when shown in a legend. |
barChart | Object | Define the properties of the barchart style. | |
barChart.align | String | 'center' | The alignment of the bars with regards to the coordinate. The options are 'left', 'right' or 'center'. |
barChart.sideBySide | Boolean | false | If two datapoints of a barchart overlap, they are drawn over eachother by default. If sideBySide is set to true, they will be drawn side by side, within the same width as a single bar.. See example 10 for more information. When using groups, see example 11. |
barChart.width | Number | 50 | The width of the bars. |
barChart.minWidth | Number | The minimum width of the bars in pixels: by default the bars get smaller while zooming out to prevent overlap, this value is the minimum width of the bar. Default behavior (when minWidth is not set) is 10% of the bar width. | |
dataAxis | Object | Define the properties of the left and right dataAxis. | |
dataAxis.alignZeros | Boolean | true | When using multiple axis, the right one is slaved to the left one. If you need to ensure that the zero-lines are on the same height, you can turn this option on. |
dataAxis.icons | Boolean | false | Toggle the drawing of automatically generated icons the Y axis. |
dataAxis.left.format | Function |
Insert a custom function on how to format the label. The function
will receive a numeric value and has to return a string. Default
function is:
function (value) { return ''+value.toPrecision(3); } |
|
dataAxis.left.range.min | Number | undefined | Set the minimum value of the left y-Axis. |
dataAxis.left.range.max | Number | undefined | Set the maximum value of the left y-Axis. |
dataAxis.left.title.style | String | undefined | Set the title style for the left axis. This is a css string and it will override the attributes set in the class. |
dataAxis.left.title.text | String | undefined | Set the title for the left axis. |
dataAxis.right.format | Function | Same explaination as the left side. | |
dataAxis.right.range.min | Number | undefined | Set the minimum value of the right y-Axis. |
dataAxis.right.range.max | Number | undefined | Set the maximum value of the right y-Axis. |
dataAxis.right.title.style | String | undefined | Set the title style for the right axis. This is a css string and it will override the attributes set in the class. |
dataAxis.right.title.text | String | undefined | Set the title for the right axis. |
dataAxis.showMinorLabels | Boolean | true | Toggle the drawing of the minor labels on the Y axis. |
dataAxis.showMajorLabels | Boolean | true | Toggle the drawing of the major labels on the Y axis. |
dataAxis.showWeekScale | Boolean | false | Toggle the drawing of the week scales on the Y axis. |
dataAxis.visible | Boolean | true | Show or hide the data axis. |
dataAxis.width | Number or String | '40px' | Set the (minimal) width of the yAxis. The axis will resize to accomodate the labels of the Y values. |
drawPoints | Boolean, Object or Function | true |
Defines rendering options for the datapoints. Three different types
of objects can be assigned to this property. See
Example 19 for
an illustration. 1. Boolean : When true is provided every datapoint will
be drawn, false otherwise.drawPoints: true // or false2. Object (the 'rendering' options): If an object is
provided it may contain following properties which all can be
optional: onRender , className size and/or style . For more information
check the property's documentation.drawPoints: { size: 3, style: 'square' }3. Function : If a function is provided it will be used
as a callback. The function may return values from listing 1 or
2.drawPoints: function(item, group) { ... }If a rendering property from the rendering option object is missing, the missing property will be fetched from the group's option. All of these three options can be defined within the drawPoints properties separately as well. |
drawPoints.enabled | Boolean | true | Toggles the drawing of the datapoints. |
drawPoints.onRender | function | none |
Defines a render function for every datapoint. If a group has no
drawPoints.onRender callback, the graph2d
drawPoints.onRender callback will be used. If neither
is defined, the datapoint will be rendered according to the group
setting of drawPoints.enabled . This callback must
return true if the datapoint should be rendered,
otherwise false .
drawPoints: { enabled: true, onRender: function(item, group, graph2d) { // only renders items with labels return item.label != null; } }This callback may also return an object containing a size and style property, both are
optional, e.g.:
onRender: function(item, group, graph2d) { if (item.label == null) { return false; } return { style: 'circle', size: 30 }; }The properties className , style and
size returned from the callback will be used for
rendering the datapoint. If a property is missing in the rendering
option object, the missing property will be fetched from the group's
option.
|
drawPoints.size | Number | 6 | Determine the size at which the data points are drawn. |
drawPoints.style | String | 'square' | Determine the shape of the data points. The options are 'square' or 'circle'. |
graphHeight | Number or String | '400px' | This is the height of the graph SVG canvas. If it is larger than the height of the outer frame, you can drag up and down the vertical direction as well as the usual horizontal direction. |
groups.visibility | Object | You can use this to toggle the visibility of groups per graph2D instance. This is different from setting the visibility flag of the groups since this is not communicated across instances of graph2d. Take a look at Example 14 for more explanation. | |
interpolation | Boolean or Object | true | Toggle the interpolation with the default settings. For more customization use the JSON format. |
interpolation.enabled | Boolean | true | Toggle the interpolation. |
interpolation.parametrization | String | 'centripetal' | Define the type of parametrizaion for the catmullRom interpolation. Example 7 shows the different parametrizations. The options are 'centripetal' (best results), 'chordal' and 'uniform'. Uniform is the computationally cheapest variant. If interpolation is disabled, linear interpolation is used. |
legend | Boolean or Object | false | Toggle the legend with the default settings. |
legend.enabled | Boolean | false | Toggle the legend. |
legend.icons | Boolean | true | Show automatically generated icons on the legend. |
legend.left.visible | Boolean | true | Both axis, left and right, have a corresponding legend. This toggles the visibility of the legend that is coupled with the left axis. |
legend.left.position | String | 'top-left' | Determine the position of the legend coupled to the left axis. Options are 'top-left', 'top-right', 'bottom-left' or 'bottom-right'. |
legend.right.visible | Boolean | true | This toggles the visibility of the legend that is coupled with the right axis. |
legend.right.position | String | 'top-right' | Determine the position of the legend coupled to the right axis. Options are 'top-left', 'top-right', 'bottom-left' or 'bottom-right'. |
moment | function | vis.moment | A constructor for creating a moment.js Date. Allows for applying a custom time zone. See section Time zone for more information. |
sampling | Boolean | true | If sampling is enabled, Graph2d will automatically determine the amount of points per pixel. If there are more than 1 point per pixel, not all points will be drawn. Disabling sampling will cause a decrease in performance. |
sort | Boolean | true | This determines if the items are sorted automatically. They are sorted by the x value. If sort is enabled, more optimizations are possible, increasing the performance. |
stack | Boolean | true | If stack is enabled, the graphs will be stacked upon each-other when applicable. A group can opt-out of stacking through the "excludeFromStacking" option. |
shaded | Boolean or Object | false | Toggle a shaded area with the default settings. |
shaded.enabled | Boolean | false | This toggles the shading. |
shaded.orientation | String | 'bottom' | This determines if the shaded area is at the bottom or at the top of the curve, or always towards the zero-axis of the graph. The options are 'zero', 'bottom', 'top', or the special case of 'group'. If group is chosen, the option groupId is required. See Example 20 what these options look like. |
shaded.groupId | String | undefined | The id of the group which should be used as the other shading limit. |
shaded.style | String | undefined | Set the style for the shading. This is a css string and it will override the attributes set in the class. |
style | String | 'line' | This allows the user to define if this should be a linegraph, barchart or pointcloud. The options are: 'line', 'bar', 'points'. |
yAxisOrientation | String | 'left' | This defines with which axis, left or right, the graph is coupled. Example 5 shows groups with different Y axis. If no groups are coupled with an axis, it will not be shown. |
excludeFromLegend | Boolean | false | Group option only. Excludes the group from being listed in the legend. |
excludeFromStacking | Boolean | false | Group option only. Excludes the group from being included in the stacking. |
Graph2d is built upon the framework of the timeline. These options from the timeline can be used with graph2D. All options are optional.
Name | Type | Default | Description |
---|---|---|---|
autoResize | Boolean | true |
If true, the Timeline will automatically detect when its container
is resized, and redraw itself accordingly. If false, the Timeline
can be forced to repaint after its container has been resized using
the function redraw() .
|
configure | boolean or function | false |
When true, a configurator is loaded where all configuration options
of the Graph2d can be changed live. The displayed options can be
filtered by providing a filter function. This function is invoked
with two arguments: the current option and the
path (an Array) of the option within the options
object. The option will be displayed when the filter function
returns true. For example to only display format options:
function (option, path) { return option === 'format' || path.indexOf('format') !== -1; } |
clickToUse | Boolean | false |
When a Graph2d is configured to be clickToUse , it will
react to mouse and touch events only when active. When active, a
blue shadow border is displayed around the Graph2d. The Graph2d is
set active by clicking on it, and is changed to inactive again by
clicking outside the Graph2d or by pressing the ESC key.
|
end | Date or Number or String | none | The initial end date for the axis of the timeline. If not provided, the latest date present in the items set is taken as end date. |
format | Object | none |
Apply custom date formatting of the labels on the time axis. The
default value of format is:
{ minorLabels: { millisecond:'SSS', second: 's', minute: 'HH:mm', hour: 'HH:mm', weekday: 'ddd D', day: 'D', week: 'w', month: 'MMM', year: 'YYYY' }, majorLabels: { millisecond:'HH:mm:ss', second: 'D MMMM HH:mm', minute: 'ddd D MMMM', hour: 'ddd D MMMM', weekday: 'MMMM YYYY', day: 'MMMM YYYY', week: 'MMMM YYYY', month: 'YYYY', year: '' } }For values which not provided in the customized options.format , the default values will be used. All
available formatting syntax is described in the
docs of moment.js.
|
height | Number or String | none |
The height of the timeline in pixels or as a percentage. When height
is undefined or null, the height of the timeline is automatically
adjusted to fit the contents. It is possible to set a maximum height
using option maxHeight
to prevent the timeline from getting too high in case of
automatically calculated height.
|
hiddenDates | Object | none |
This option allows you to hide specific timespans from the time
axis. The dates can be supplied as an object:
{start: '2014-03-21 00:00:00', end: '2014-03-28 00:00:00',
[repeat:'daily']}
or as an Array of these objects. The repeat argument is optional.
The possible values are (case-sensitive):
daily, weekly, monthly, yearly . To hide a weekend, pick
any Saturday as start and the following Monday as end and set repeat
to weekly.
|
locale | String | none | Select a locale for the Graph2d. See section Localization for more information. |
locales | Object | none | A map with i18n locales. See section Localization for more information. |
max | Date or Number or String | none | Set a maximum Date for the visible range. It will not be possible to move beyond this maximum. |
maxHeight | Number or String | none | Specifies the maximum height for the Timeline. Can be a number in pixels or a string like "300px". |
maxMinorChars | number | 7 | Specifies the maximum number of characters that should fit in minor grid labels. If larger, less and wider grids will be drawn. |
min | Date or Number or String | none | Set a minimum Date for the visible range. It will not be possible to move beyond this minimum. |
minHeight | Number or String | none | Specifies the minimum height for the Timeline. Can be a number in pixels or a string like "300px". |
moveable | boolean | true |
Specifies whether the Timeline can be moved and zoomed by dragging
the window. See also option zoomable .
|
orientation | String | 'bottom' | Orientation of the timeline: 'top', 'bottom' (default), or 'both'. If orientation is 'bottom', the time axis is drawn at the bottom. When 'top', the axis is drawn on top. When 'both', two axes are drawn, both on top and at the bottom. |
showCurrentTime | Boolean | true | Show a vertical bar at the current time. |
showCustomTime | Boolean | false |
Show a vertical bar displaying a custom time. This line can be
dragged by the user. The custom time can be utilized to show a state
in the past or in the future. When the custom time bar is dragged by
the user, the event timechange is fired repeatedly.
After the bar is dragged, the event timechanged is
fired once.
|
showMajorLabels | Boolean | true |
By default, the timeline shows both minor and major date labels on
the time axis. For example the minor labels show minutes and the
major labels show hours. When showMajorLabels is
false , no major labels are shown.
|
showMinorLabels | Boolean | true |
By default, the timeline shows both minor and major date labels on
the time axis. For example the minor labels show minutes and the
major labels show hours. When showMinorLabels is
false , no minor labels are shown. When both
showMajorLabels and showMinorLabels are
false, no horizontal axis will be visible.
|
start | Date or Number or String | none | The initial start date for the axis of the timeline. If not provided, the earliest date present in the events is taken as start date. |
timeAxis | Object | Object |
Specify a fixed scale and step size for the time axis. |
timeAxis.scale | String | none |
Set a fixed scale for the time axis of the Timeline. Choose from
'millisecond' , 'second' ,
'minute' , 'hour' , 'weekday' ,
'day' , 'month' , 'year' .
Example usage:
var options = { timeAxis: {scale: 'minute', step: 5} } |
timeAxis.step | number | 1 |
Set a fixed step size for the time axis. Only applicable when used
together with timeAxis.scale . Choose for example 1, 2,
5, or 10.
|
width | String | '100%' | The width of the timeline in pixels or as a percentage. |
zoomable | boolean | true |
Specifies whether the Timeline can be zoomed by pinching or
scrolling in the window. Only applicable when option
moveable is set .
|
zoomKey | String | '' |
Specifies whether the Timeline is only zoomed when an additional key
is down. Available values are '' (does not apply), 'altKey',
'ctrlKey', or 'metaKey'. Only applicable when option
moveable is set .
|
zoomMax | Number | 315360000000000 | Set a maximum zoom interval for the visible range in milliseconds. It will not be possible to zoom out further than this maximum. Default value equals about 10000 years. |
zoomMin | Number | 10 | Set a minimum zoom interval for the visible range in milliseconds. It will not be possible to zoom in further than this minimum. |
The Graph2d supports the following methods.
Method | Return Type | Description |
---|---|---|
destroy() | none | Destroy the Graph2d. The Graph2d is removed from memory. all DOM elements and event listeners are cleaned up. |
fit() | none | Adjust the visible window such that it fits all items. |
getCurrentTime() | Date |
Get the current time. Only applicable when option
showCurrentTime is true.
|
getCustomTime() | Date |
Retrieve the custom time. Only applicable when the option
showCustomTime is true.
|
getDataRange() | Object |
Get the range of all the items as an object containing
min: Date and max: Date .
|
getEventProperties(event) | Object |
Returns an Object with relevant properties from an event:
|
getLegend(groupId, iconWidth, iconHeight) | SVGelement, String, String | Returns an object containing an SVG element with the icon of the group (size determined by iconWidth and iconHeight), the label of the group (content) and the yAxisOrientation of the group (left or right). |
getWindow() | Object |
Get the current visible window. Returns an object with properties
start: Date and end: Date .
|
isGroupVisible(groupId) | Boolean | This checks if the visible option of the supplied group (by ID) is true or false. |
moveTo(time [, options]) | none |
Move the window such that given time is centered on screen.
Parameter time can be a Date ,
Number , or String . Available options:
|
on(event, callback) | none |
Create an event listener. The callback function is invoked every
time the event is triggered. Available events:
rangechange , rangechanged ,
select . The callback function is invoked as
callback(properties) , where properties is
an object containing event specific properties. See section
Events for more information.
|
off(event, callback) | none |
Remove an event listener created before via function
on(event, callback) . See section
Events for more information.
|
redraw() | none | Force a redraw of the Graph2d. Can be useful to manually redraw when option autoResize=false. |
setCurrentTime(time) | none |
Set a current time. This can be used for example to ensure that a
client's time is synchronized with a shared server time.
time can be a Date object, numeric timestamp, or ISO
date string. Only applicable when option
showCurrentTime is true.
|
setCustomTime(time) | none |
Adjust the custom time bar. Only applicable when the option
showCustomTime is true. time can be a Date
object, numeric timestamp, or ISO date string.
|
setGroups(groups) | none |
Set a data set with groups for the Graph2d. groups can
be an Array with Objects, a DataSet, or a DataView. For each of the
groups, the items of the Graph2d are filtered on the property
group , which must correspond with the id of the group.
|
setItems(items) | none |
Set a data set with items for the Graph2d. items can be
an Array with Objects, a DataSet, or a DataView.
|
setOptions(options) | none | Set or update options. It is possible to change any option of the Graph2d at any time. You can for example switch orientation on the fly. |
setWindow(start, end) | none |
Set the current visible window. The parameters
start and end can be a Date ,
Number , or String . If the parameter value
of start or end is null, the parameter
will be left unchanged.
|
Graph2d fires events when changing the visible window by dragging, when selecting items, and when dragging the custom time bar.
Here an example on how to listen for a rangeChanged
event.
A listener can be removed via the function off
:
function onChange (properties) { alert('changed!'); } // add event listener Graph2d.on('rangechanged', onChange); // do stuff... // remove event listener Graph2d.off('rangechanged', onChange);
The following events are available.
Name | Properties | Description |
---|---|---|
currentTimeTick | Fired when the current time bar redraws. The rate depends on the zoom level. | |
click |
Passes a properties object as returned by the method
Graph2d.getEventProperties(event) .
|
Fired when clicked inside the Graph2d. |
contextmenu |
Passes a properties object as returned by the method
Graph2d.getEventProperties(event) .
|
Fired when right-clicked inside the Graph2d. Note that in order to
prevent the context menu from showing up, default behavior of the
event must be stopped:
graph2d.on('contextmenu', function (props) { alert('Right click!'); props.event.preventDefault(); }); |
doubleClick |
Passes a properties object as returned by the method
Graph2d.getEventProperties(event) .
|
Fired when double clicked inside the Graph2d. |
changed | Has no properties. | Fired once after each graph redraw. |
rangechange |
|
Fired repeatedly when the user is dragging the Graph2d window. |
rangechanged |
|
Fired once after the user has dragged the Graph2d window. |
timechange |
|
Fired repeatedly when the user is dragging the custom time bar. Only available when the custom time bar is enabled. |
timechanged |
|
Fired once after the user has dragged the custom time bar. Only available when the custom time bar is enabled. |
Graph2d can be localized. For localization, Graph2d depends largely on the localization of moment.js. Locales are not included in vis.js by default. To enable localization, moment.js must be loaded with locales. Moment.js offers a bundle named "moment-with-locales.min.js" for this and there are various alternative ways to load locales.
To set a locale for the Graph2d, specify the option locale
:
var options = { locale: 'nl' };
locales
:
var options = { locales: { // create a new locale mylocale: { current: 'current', time: 'time', } }, // use the new locale locale: 'mylocale' };
Language | Code |
English |
en en_EN en_US
|
Dutch |
nl nl_NL nl_BE
|
By default, the Timeline displays time in local time. To display a
Timeline in an other time zone or in UTC, the date constructor can be
overloaded via the configuration option moment
, which by
default is the constructor function of moment.js. More information about
UTC with moment.js can be found in the docs:
http://momentjs.com/docs/#/parsing/utc/.
Examples:
// display in UTC var options = { moment: function(date) { return vis.moment(date).utc(); } }; // display in UTC +08:00 var options = { moment: function(date) { return vis.moment(date).utcOffset('+08:00'); } };
All parts of the Graph2d have a class name and a default css style just like the Graph2d. The styles can be overwritten, which enables full customization of the layout of the Graph2d.
Additionally, Graph2d has 10 preset styles for graphs, which are cycled through when loading groups. These styles can be overwritten as well, along with defining your own classes to style the graphs! Example 4 and example 5 show the usage of custom styles.