Chartist - API Documentation
axis.js
Module Chartist.Axis
Axis base class used to implement different axis types
linear-scale-axis.js
Module Chartist.LinearScaleAxis
The linear scale axis uses standard linear scale projection of values along an axis.
step-axis.js
Module Chartist.StepAxis
Step axis for step based charts like bar chart or step based line chart
base.js
Module Chartist.Base
Base for all chart types. The methods in Chartist.Base are inherited to all chart types.
function update()
function update(data, options, override) {
if(data) {
this.data = data;
// Event for data transformation that allows to manipulate the data before it gets rendered in the charts
this.eventEmitter.emit('data', {
type: 'update',
data: this.data
});
}
if(options) {
this.options = Chartist.extend({}, override ? this.options : this.defaultOptions, options);
// If chartist was not initialized yet, we just set the options and leave the rest to the initialization
// Otherwise we re-create the optionsProvider at this point
if(!this.initializeTimeoutId) {
this.optionsProvider.removeMediaQueryListeners();
this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
}
}
// Only re-created the chart if it has been initialized yet
if(!this.initializeTimeoutId) {
this.createChart(this.optionsProvider.currentOptions);
}
// Return a reference to the chart object to chain up calls
return this;
}
Updates the chart which currently does a full reconstruction of the SVG DOM
Parameters
[data] ( Object )[options] ( Object )[override] ( Boolean )function detach()
function detach() {
window.removeEventListener('resize', this.resizeListener);
this.optionsProvider.removeMediaQueryListeners();
return this;
}
This method can be called on the API object of each chart and will un-register all event listeners that were added to other components. This currently includes a window.resize listener as well as media query listeners if any responsive options have been provided. Use this function if you need to destroy and recreate Chartist charts dynamically.
function on()
function on(event, handler) {
this.eventEmitter.addEventHandler(event, handler);
return this;
}
Use this function to register event handlers. The handler callbacks are synchronous and will run in the main thread rather than the event loop.
Parameters
event ( String )handler ( Function )function off()
function off(event, handler) {
this.eventEmitter.removeEventHandler(event, handler);
return this;
}
function initialize() {
// Add window resize listener that re-creates the chart
window.addEventListener('resize', this.resizeListener);
// Obtain current options based on matching media queries (if responsive options are given)
// This will also register a listener that is re-creating the chart based on media changes
this.optionsProvider = Chartist.optionsProvider(this.options, this.responsiveOptions, this.eventEmitter);
// Register options change listener that will trigger a chart update
this.eventEmitter.addEventHandler('optionsChanged', function() {
this.update();
}.bind(this));
// Before the first chart creation we need to register us with all plugins that are configured
// Initialize all relevant plugins with our chart object and the plugin options specified in the config
if(this.options.plugins) {
this.options.plugins.forEach(function(plugin) {
if(plugin instanceof Array) {
plugin[0](this, plugin[1]);
} else {
plugin(this);
}
}.bind(this));
}
// Event for data transformation that allows to manipulate the data before it gets rendered in the charts
this.eventEmitter.emit('data', {
type: 'initial',
data: this.data
});
// Create the first chart
this.createChart(this.optionsProvider.currentOptions);
// As chart is initialized from the event loop now we can reset our timeout reference
// This is important if the chart gets initialized on the same element twice
this.initializeTimeoutId = undefined;
}
Use this function to un-register event handlers. If the handler function parameter is omitted all handlers for the given event will be un-registered.
Parameters
event ( String )[handler] ( Function )bar.js
Module Chartist.Bar
The bar chart module of Chartist that can be used to draw unipolar or bipolar bar and grouped bar charts.
declaration defaultOptions
var defaultOptions = {
// Options for X-Axis
axisX: {
// The offset of the chart drawing area to the border of the container
offset: 30,
// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset: {
x: 0,
y: 0
},
// If labels should be shown or not
showLabel: true,
// If the axis grid should be drawn or not
showGrid: true,
// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc: Chartist.noop,
// This value specifies the minimum width in pixel of the scale steps
scaleMinSpace: 40
},
// Options for Y-Axis
axisY: {
// The offset of the chart drawing area to the border of the container
offset: 40,
// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset: {
x: 0,
y: 0
},
// If labels should be shown or not
showLabel: true,
// If the axis grid should be drawn or not
showGrid: true,
// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc: Chartist.noop,
// This value specifies the minimum height in pixel of the scale steps
scaleMinSpace: 20
},
// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width: undefined,
// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height: undefined,
// Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
high: undefined,
// Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
low: undefined,
// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding: 5,
// Specify the distance in pixel of bars in a group
seriesBarDistance: 15,
// If set to true this property will cause the series bars to be stacked and form a total for each series point. This will also influence the y-axis and the overall bounds of the chart. In stacked mode the seriesBarDistance property will have no effect.
stackBars: false,
// Inverts the axes of the bar chart in order to draw a horizontal bar chart. Be aware that you also need to invert your axis settings as the Y Axis will now display the labels and the X Axis the values.
horizontalBars: false,
// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData: false,
// Override the class names that get used to generate the SVG structure of the chart
classNames: {
chart: 'ct-chart-bar',
label: 'ct-label',
labelGroup: 'ct-labels',
series: 'ct-series',
bar: 'ct-bar',
grid: 'ct-grid',
gridGroup: 'ct-grids',
vertical: 'ct-vertical',
horizontal: 'ct-horizontal'
}
};
Default options in bar charts. Expand the code view to see a detailed list of options with comments.
function Bar()
function Bar(query, data, options, responsiveOptions) {
Chartist.Bar.super.constructor.call(this,
query,
data,
defaultOptions,
Chartist.extend({}, defaultOptions, options),
responsiveOptions);
}
// Creating bar chart type in Chartist namespace
Chartist.Bar = Chartist.Base.extend({
constructor: Bar,
createChart: createChart
});
}(window, document, Chartist));
This method creates a new bar chart and returns API object that you can use for later changes.
Parameters
query ( String Node )data ( Object )[options] ( Object )[responsiveOptions] ( Array )Returns
Object )Examples
// Create a simple bar chart
var data = {
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [
[5, 2, 4, 2, 0]
]
};
// In the global name space Chartist we call the Bar function to initialize a bar chart. As a first parameter we pass in a selector where we would like to get our chart created and as a second parameter we pass our data object.
new Chartist.Bar('.ct-chart', data);
// This example creates a bipolar grouped bar chart where the boundaries are limitted to -10 and 10
new Chartist.Bar('.ct-chart', {
labels: [1, 2, 3, 4, 5, 6, 7],
series: [
[1, 3, 2, -5, -3, 1, -6],
[-5, -2, -4, -1, 2, -3, 1]
]
}, {
seriesBarDistance: 12,
low: -10,
high: 10
});line.js
Module Chartist.Line
The Chartist line chart can be used to draw Line or Scatter charts. If used in the browser you can access the global Chartist namespace where you find the Line function as a main entry point.
declaration defaultOptions
var defaultOptions = {
// Options for X-Axis
axisX: {
// The offset of the labels to the chart area
offset: 30,
// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset: {
x: 0,
y: 0
},
// If labels should be shown or not
showLabel: true,
// If the axis grid should be drawn or not
showGrid: true,
// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc: Chartist.noop
},
// Options for Y-Axis
axisY: {
// The offset of the labels to the chart area
offset: 40,
// Allows you to correct label positioning on this axis by positive or negative x and y offset.
labelOffset: {
x: 0,
y: 0
},
// If labels should be shown or not
showLabel: true,
// If the axis grid should be drawn or not
showGrid: true,
// Interpolation function that allows you to intercept the value from the axis label
labelInterpolationFnc: Chartist.noop,
// This value specifies the minimum height in pixel of the scale steps
scaleMinSpace: 20
},
// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width: undefined,
// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height: undefined,
// If the line should be drawn or not
showLine: true,
// If dots should be drawn or not
showPoint: true,
// If the line chart should draw an area
showArea: false,
// The base for the area chart that will be used to close the area shape (is normally 0)
areaBase: 0,
// Specify if the lines should be smoothed. This value can be true or false where true will result in smoothing using the default smoothing interpolation function Chartist.Interpolation.cardinal and false results in Chartist.Interpolation.none. You can also choose other smoothing / interpolation functions available in the Chartist.Interpolation module, or write your own interpolation function. Check the examples for a brief description.
lineSmooth: true,
// Overriding the natural low of the chart allows you to zoom in or limit the charts lowest displayed value
low: undefined,
// Overriding the natural high of the chart allows you to zoom in or limit the charts highest displayed value
high: undefined,
// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding: 5,
// When set to true, the last grid line on the x-axis is not drawn and the chart elements will expand to the full available width of the chart. For the last label to be drawn correctly you might need to add chart padding or offset the last label with a draw event handler.
fullWidth: false,
// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData: false,
// Override the class names that get used to generate the SVG structure of the chart
classNames: {
chart: 'ct-chart-line',
label: 'ct-label',
labelGroup: 'ct-labels',
series: 'ct-series',
line: 'ct-line',
point: 'ct-point',
area: 'ct-area',
grid: 'ct-grid',
gridGroup: 'ct-grids',
vertical: 'ct-vertical',
horizontal: 'ct-horizontal'
}
};
Default options in line charts. Expand the code view to see a detailed list of options with comments.
function Line()
function Line(query, data, options, responsiveOptions) {
Chartist.Line.super.constructor.call(this,
query,
data,
defaultOptions,
Chartist.extend({}, defaultOptions, options),
responsiveOptions);
}
// Creating line chart type in Chartist namespace
Chartist.Line = Chartist.Base.extend({
constructor: Line,
createChart: createChart
});
}(window, document, Chartist));
This method creates a new line chart.
Parameters
query ( String Node )data ( Object )[options] ( Object )[responsiveOptions] ( Array )Returns
Object )Examples
// Create a simple line chart
var data = {
// A labels array that can contain any sort of values
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
// Our series array that contains series objects or in this case series data arrays
series: [
[5, 2, 4, 2, 0]
]
};
// As options we currently only set a static size of 300x200 px
var options = {
width: '300px',
height: '200px'
};
// In the global name space Chartist we call the Line function to initialize a line chart. As a first parameter we pass in a selector where we would like to get our chart created. Second parameter is the actual data object and as a third parameter we pass in our options
new Chartist.Line('.ct-chart', data, options);
// Use specific interpolation function with configuration from the Chartist.Interpolation module
var chart = new Chartist.Line('.ct-chart', {
labels: [1, 2, 3, 4, 5],
series: [
[1, 1, 8, 1, 7]
]
}, {
lineSmooth: Chartist.Interpolation.cardinal({
tension: 0.2
})
});
// Create a line chart with responsive options
var data = {
// A labels array that can contain any sort of values
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'],
// Our series array that contains series objects or in this case series data arrays
series: [
[5, 2, 4, 2, 0]
]
};
// In adition to the regular options we specify responsive option overrides that will override the default configutation based on the matching media queries.
var responsiveOptions = [
['screen and (min-width: 641px) and (max-width: 1024px)', {
showPoint: false,
axisX: {
labelInterpolationFnc: function(value) {
// Will return Mon, Tue, Wed etc. on medium screens
return value.slice(0, 3);
}
}
}],
['screen and (max-width: 640px)', {
showLine: false,
axisX: {
labelInterpolationFnc: function(value) {
// Will return M, T, W etc. on small screens
return value[0];
}
}
}]
];
new Chartist.Line('.ct-chart', data, null, responsiveOptions);pie.js
Module Chartist.Pie
The pie chart module of Chartist that can be used to draw pie, donut or gauge charts
declaration defaultOptions
var defaultOptions = {
// Specify a fixed width for the chart as a string (i.e. '100px' or '50%')
width: undefined,
// Specify a fixed height for the chart as a string (i.e. '100px' or '50%')
height: undefined,
// Padding of the chart drawing area to the container element and labels as a number or padding object {top: 5, right: 5, bottom: 5, left: 5}
chartPadding: 5,
// Override the class names that get used to generate the SVG structure of the chart
classNames: {
chart: 'ct-chart-pie',
series: 'ct-series',
slice: 'ct-slice',
donut: 'ct-donut',
label: 'ct-label'
},
// The start angle of the pie chart in degrees where 0 points north. A higher value offsets the start angle clockwise.
startAngle: 0,
// An optional total you can specify. By specifying a total value, the sum of the values in the series must be this total in order to draw a full pie. You can use this parameter to draw only parts of a pie or gauge charts.
total: undefined,
// If specified the donut CSS classes will be used and strokes will be drawn instead of pie slices.
donut: false,
// Specify the donut stroke width, currently done in javascript for convenience. May move to CSS styles in the future.
donutWidth: 60,
// If a label should be shown or not
showLabel: true,
// Label position offset from the standard position which is half distance of the radius. This value can be either positive or negative. Positive values will position the label away from the center.
labelOffset: 0,
// An interpolation function for the label value
labelInterpolationFnc: Chartist.noop,
// Label direction can be 'neutral', 'explode' or 'implode'. The labels anchor will be positioned based on those settings as well as the fact if the labels are on the right or left side of the center of the chart. Usually explode is useful when labels are positioned far away from the center.
labelDirection: 'neutral',
// If true the whole data is reversed including labels, the series order as well as the whole series data arrays.
reverseData: false
};
Default options in line charts. Expand the code view to see a detailed list of options with comments.
function Pie()
function Pie(query, data, options, responsiveOptions) {
Chartist.Pie.super.constructor.call(this,
query,
data,
defaultOptions,
Chartist.extend({}, defaultOptions, options),
responsiveOptions);
}
// Creating pie chart type in Chartist namespace
Chartist.Pie = Chartist.Base.extend({
constructor: Pie,
createChart: createChart,
determineAnchorPosition: determineAnchorPosition
});
}(window, document, Chartist));
This method creates a new pie chart and returns an object that can be used to redraw the chart.
Parameters
query ( String Node )data ( Object )[options] ( Object )[responsiveOptions] ( Array )Returns
Object )Examples
// Simple pie chart example with four series
new Chartist.Pie('.ct-chart', {
series: [10, 2, 4, 3]
});
// Drawing a donut chart
new Chartist.Pie('.ct-chart', {
series: [10, 2, 4, 3]
}, {
donut: true
});
// Using donut, startAngle and total to draw a gauge chart
new Chartist.Pie('.ct-chart', {
series: [20, 10, 30, 40]
}, {
donut: true,
donutWidth: 20,
startAngle: 270,
total: 200
});
// Drawing a pie chart with padding and labels that are outside the pie
new Chartist.Pie('.ct-chart', {
series: [20, 10, 30, 40]
}, {
chartPadding: 30,
labelOffset: 50,
labelDirection: 'explode'
});
// Overriding the class names for individual series
new Chartist.Pie('.ct-chart', {
series: [{
data: 20,
className: 'my-custom-class-one'
}, {
data: 10,
className: 'my-custom-class-two'
}, {
data: 70,
className: 'my-custom-class-three'
}]
});class.js
Module Chartist.Class
This module provides some basic prototype inheritance utilities.
function extend()
function extend(properties, superProtoOverride) {
var superProto = superProtoOverride || this.prototype || Chartist.Class;
var proto = Object.create(superProto);
Chartist.Class.cloneDefinitions(proto, properties);
var constr = function() {
var fn = proto.constructor || function () {},
instance;
// If this is linked to the Chartist namespace the constructor was not called with new
// To provide a fallback we will instantiate here and return the instance
instance = this === Chartist ? Object.create(proto) : this;
fn.apply(instance, Array.prototype.slice.call(arguments, 0));
// If this constructor was not called with new we need to return the instance
// This will not harm when the constructor has been called with new as the returned value is ignored
return instance;
};
constr.prototype = proto;
constr.super = superProto;
constr.extend = this.extend;
return constr;
}
// Variable argument list clones args > 0 into args[0] and retruns modified args[0]
function cloneDefinitions() {
var args = listToArray(arguments);
var target = args[0];
args.splice(1, args.length - 1).forEach(function (source) {
Object.getOwnPropertyNames(source).forEach(function (propName) {
// If this property already exist in target we delete it first
delete target[propName];
// Define the property with the descriptor from source
Object.defineProperty(target, propName,
Object.getOwnPropertyDescriptor(source, propName));
});
});
return target;
}
Chartist.Class = {
extend: extend,
cloneDefinitions: cloneDefinitions
};
}(window, document, Chartist));
Method to extend from current prototype.
Parameters
properties ( Object )[superProtoOverride] ( Object )Returns
Function )Examples
var Fruit = Class.extend({
color: undefined,
sugar: undefined,
constructor: function(color, sugar) {
this.color = color;
this.sugar = sugar;
},
eat: function() {
this.sugar = 0;
return this;
}
});
var Banana = Fruit.extend({
length: undefined,
constructor: function(length, sugar) {
Banana.super.constructor.call(this, 'Yellow', sugar);
this.length = length;
}
});
var banana = new Banana(20, 40);
console.log('banana instanceof Fruit', banana instanceof Fruit);
console.log('Fruit is prototype of banana', Fruit.prototype.isPrototypeOf(banana));
console.log('bananas prototype is Fruit', Object.getPrototypeOf(banana) === Fruit.prototype);
console.log(banana.sugar);
console.log(banana.eat().sugar);
console.log(banana.color);core.js
Module Chartist.Core
The core module of Chartist that is mainly providing static functions and higher level functions for chart modules.
method Chartist.noop()
Chartist.noop = function (n) {
return n;
};
Helps to simplify functional style code
Parameters
n ( * )Returns
* )method Chartist.alphaNumerate()
Chartist.alphaNumerate = function (n) {
// Limit to a-z
return String.fromCharCode(97 + n % 26);
};
Generates a-z from a number 0 to 26
Parameters
n ( Number )Returns
String )method Chartist.extend()
Chartist.extend = function (target) {
target = target || {};
var sources = Array.prototype.slice.call(arguments, 1);
sources.forEach(function(source) {
for (var prop in source) {
if (typeof source[prop] === 'object' && !(source[prop] instanceof Array)) {
target[prop] = Chartist.extend({}, target[prop], source[prop]);
} else {
target[prop] = source[prop];
}
}
});
return target;
};
Simple recursive object extend
Parameters
target ( Object )sources ( Object... )Returns
Object )method Chartist.replaceAll()
Chartist.replaceAll = function(str, subStr, newSubStr) {
return str.replace(new RegExp(subStr, 'g'), newSubStr);
};
Replaces all occurrences of subStr in str with newSubStr and returns a new string.
Parameters
str ( String )subStr ( String )newSubStr ( String )Returns
String )method Chartist.stripUnit()
Chartist.stripUnit = function(value) {
if(typeof value === 'string') {
value = value.replace(/[^0-9\+-\.]/g, '');
}
return +value;
};
Converts a string to a number while removing the unit if present. If a number is passed then this will be returned unmodified.
Parameters
value ( String Number )Returns
Number )method Chartist.ensureUnit()
Chartist.ensureUnit = function(value, unit) {
if(typeof value === 'number') {
value = value + unit;
}
return value;
};
Converts a number to a string with a unit. If a string is passed then this will be returned unmodified.
Parameters
value ( Number )unit ( String )Returns
String )method Chartist.querySelector()
Chartist.querySelector = function(query) {
return query instanceof Node ? query : document.querySelector(query);
};
This is a wrapper around document.querySelector that will return the query if it's already of type Node
Parameters
query ( String Node )Returns
Node )method Chartist.times()
Chartist.times = function(length) {
return Array.apply(null, new Array(length));
};
Functional style helper to produce array with given length initialized with undefined values
Parameters
( length )Returns
Array )method Chartist.sum()
Chartist.sum = function(previous, current) {
return previous + current;
};
Sum helper to be used in reduce functions
Parameters
( previous ) ( current )Returns
* )method Chartist.serialMap()
Chartist.serialMap = function(arr, cb) {
var result = [],
length = Math.max.apply(null, arr.map(function(e) {
return e.length;
}));
Chartist.times(length).forEach(function(e, index) {
var args = arr.map(function(e) {
return e[index];
});
result[index] = cb.apply(null, args);
});
return result;
};
Map for multi dimensional arrays where their nested arrays will be mapped in serial. The output array will have the length of the largest nested array. The callback function is called with variable arguments where each argument is the nested array value (or undefined if there are no more values).
Parameters
( arr ) ( cb )Returns
Array )method Chartist.roundWithPrecision()
Chartist.roundWithPrecision = function(value, digits) {
var precision = Math.pow(10, digits || Chartist.precision);
return Math.round(value * precision) / precision;
};
This helper function can be used to round values with certain precision level after decimal. This is used to prevent rounding errors near float point precision limit.
Parameters
value ( Number )[digits] ( Number )property Chartist.precision
Chartist.precision = 8;
Precision level used internally in Chartist for rounding. If you require more decimal places you can increase this number.
property Chartist.escapingMap
Chartist.escapingMap = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
'\'': '''
};
A map with characters to escape for strings to be safely used as attribute values.
method Chartist.serialize()
Chartist.serialize = function(data) {
if(data === null || data === undefined) {
return data;
} else if(typeof data === 'number') {
data = ''+data;
} else if(typeof data === 'object') {
data = JSON.stringify({data: data});
}
return Object.keys(Chartist.escapingMap).reduce(function(result, key) {
return Chartist.replaceAll(result, key, Chartist.escapingMap[key]);
}, data);
};
This function serializes arbitrary data to a string. In case of data that can't be easily converted to a string, this function will create a wrapper object and serialize the data using JSON.stringify. The outcoming string will always be escaped using Chartist.escapingMap.
If called with null or undefined the function will return immediately with null or undefined.
Parameters
data ( Number String Object )Returns
String )method Chartist.deserialize()
Chartist.deserialize = function(data) {
if(typeof data !== 'string') {
return data;
}
data = Object.keys(Chartist.escapingMap).reduce(function(result, key) {
return Chartist.replaceAll(result, Chartist.escapingMap[key], key);
}, data);
try {
data = JSON.parse(data);
data = data.data !== undefined ? data.data : data;
} catch(e) {}
return data;
};
This function de-serializes a string previously serialized with Chartist.serialize. The string will always be unescaped using Chartist.escapingMap before it's returned. Based on the input value the return type can be Number, String or Object. JSON.parse is used with try / catch to see if the unescaped string can be parsed into an Object and this Object will be returned on success.
Parameters
data ( String )Returns
String Number Object )method Chartist.createSvg()
Chartist.createSvg = function (container, width, height, className) {
var svg;
width = width || '100%';
height = height || '100%';
// Check if there is a previous SVG element in the container that contains the Chartist XML namespace and remove it
// Since the DOM API does not support namespaces we need to manually search the returned list http://www.w3.org/TR/selectors-api/
Array.prototype.slice.call(container.querySelectorAll('svg')).filter(function filterChartistSvgObjects(svg) {
return svg.getAttribute(Chartist.xmlNs.qualifiedName);
}).forEach(function removePreviousElement(svg) {
container.removeChild(svg);
});
// Create svg object with width and height or use 100% as default
svg = new Chartist.Svg('svg').attr({
width: width,
height: height
}).addClass(className).attr({
style: 'width: ' + width + '; height: ' + height + ';'
});
// Add the DOM node to our container
container.appendChild(svg._node);
return svg;
};
Create or reinitialize the SVG element for the chart
Parameters
container ( Node )width ( String )height ( String )className ( String )Returns
Object )method Chartist.reverseData()
Chartist.reverseData = function(data) {
data.labels.reverse();
data.series.reverse();
for (var i = 0; i < data.series.length; i++) {
if(typeof(data.series[i]) === 'object' && data.series[i].data !== undefined) {
data.series[i].data.reverse();
} else {
data.series[i].reverse();
}
}
};
Reverses the series, labels and series data arrays.
Parameters
( data )method Chartist.getDataArray()
Chartist.getDataArray = function (data, reverse) {
var array = [],
value,
localData;
// If the data should be reversed but isn't we need to reverse it
// If it's reversed but it shouldn't we need to reverse it back
// That's required to handle data updates correctly and to reflect the responsive configurations
if(reverse && !data.reversed || !reverse && data.reversed) {
Chartist.reverseData(data);
data.reversed = !data.reversed;
}
for (var i = 0; i < data.series.length; i++) {
// If the series array contains an object with a data property we will use the property
// otherwise the value directly (array or number).
// We create a copy of the original data array with Array.prototype.push.apply
localData = typeof(data.series[i]) === 'object' && data.series[i].data !== undefined ? data.series[i].data : data.series[i];
if(localData instanceof Array) {
array[i] = [];
Array.prototype.push.apply(array[i], localData);
} else {
array[i] = localData;
}
// Convert object values to numbers
for (var j = 0; j < array[i].length; j++) {
value = array[i][j];
value = value.value === 0 ? 0 : (value.value || value);
array[i][j] = +value;
}
}
return array;
};
Convert data series into plain array
Parameters
data ( Object )reverse ( Boolean )Returns
Array )method Chartist.normalizePadding()
Chartist.normalizePadding = function(padding, fallback) {
fallback = fallback || 0;
return typeof padding === 'number' ? {
top: padding,
right: padding,
bottom: padding,
left: padding
} : {
top: typeof padding.top === 'number' ? padding.top : fallback,
right: typeof padding.right === 'number' ? padding.right : fallback,
bottom: typeof padding.bottom === 'number' ? padding.bottom : fallback,
left: typeof padding.left === 'number' ? padding.left : fallback
};
};
Converts a number into a padding object.
Parameters
padding ( Object Number )[fallback] ( Number )method Chartist.normalizeDataArray()
Chartist.normalizeDataArray = function (dataArray, length) {
for (var i = 0; i < dataArray.length; i++) {
if (dataArray[i].length === length) {
continue;
}
for (var j = dataArray[i].length; j < length; j++) {
dataArray[i][j] = 0;
}
}
return dataArray;
};
Chartist.getMetaData = function(series, index) {
var value = series.data ? series.data[index] : series[index];
return value ? Chartist.serialize(value.meta) : undefined;
};
Adds missing values at the end of the array. This array contains the data, that will be visualized in the chart
Parameters
dataArray ( Array )length ( Number )Returns
Array )method Chartist.orderOfMagnitude()
Chartist.orderOfMagnitude = function (value) {
return Math.floor(Math.log(Math.abs(value)) / Math.LN10);
};
Calculate the order of magnitude for the chart scale
Parameters
value ( Number )Returns
Number )method Chartist.projectLength()
Chartist.projectLength = function (axisLength, length, bounds) {
return length / bounds.range * axisLength;
};
Project a data length into screen coordinates (pixels)
Parameters
axisLength ( Object )length ( Number )bounds ( Object )Returns
Number )method Chartist.getAvailableHeight()
Chartist.getAvailableHeight = function (svg, options) {
return Math.max((Chartist.stripUnit(options.height) || svg.height()) - (options.chartPadding.top + options.chartPadding.bottom) - options.axisX.offset, 0);
};
Get the height of the area in the chart for the data series
Parameters
svg ( Object )options ( Object )Returns
Number )method Chartist.getHighLow()
Chartist.getHighLow = function (dataArray) {
var i,
j,
highLow = {
high: -Number.MAX_VALUE,
low: Number.MAX_VALUE
};
for (i = 0; i < dataArray.length; i++) {
for (j = 0; j < dataArray[i].length; j++) {
if (dataArray[i][j] > highLow.high) {
highLow.high = dataArray[i][j];
}
if (dataArray[i][j] < highLow.low) {
highLow.low = dataArray[i][j];
}
}
}
return highLow;
};
Get highest and lowest value of data array. This Array contains the data that will be visualized in the chart.
Parameters
dataArray ( Array )Returns
Object )method Chartist.getBounds()
Chartist.getBounds = function (axisLength, highLow, scaleMinSpace, referenceValue) {
var i,
newMin,
newMax,
bounds = {
high: highLow.high,
low: highLow.low
};
// If high and low are the same because of misconfiguration or flat data (only the same value) we need
// to set the high or low to 0 depending on the polarity
if(bounds.high === bounds.low) {
// If both values are 0 we set high to 1
if(bounds.low === 0) {
bounds.high = 1;
} else if(bounds.low < 0) {
// If we have the same negative value for the bounds we set bounds.high to 0
bounds.high = 0;
} else {
// If we have the same positive value for the bounds we set bounds.low to 0
bounds.low = 0;
}
}
// Overrides of high / low based on reference value, it will make sure that the invisible reference value is
// used to generate the chart. This is useful when the chart always needs to contain the position of the
// invisible reference value in the view i.e. for bipolar scales.
if (referenceValue || referenceValue === 0) {
bounds.high = Math.max(referenceValue, bounds.high);
bounds.low = Math.min(referenceValue, bounds.low);
}
bounds.valueRange = bounds.high - bounds.low;
bounds.oom = Chartist.orderOfMagnitude(bounds.valueRange);
bounds.min = Math.floor(bounds.low / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom);
bounds.max = Math.ceil(bounds.high / Math.pow(10, bounds.oom)) * Math.pow(10, bounds.oom);
bounds.range = bounds.max - bounds.min;
bounds.step = Math.pow(10, bounds.oom);
bounds.numberOfSteps = Math.round(bounds.range / bounds.step);
// Optimize scale step by checking if subdivision is possible based on horizontalGridMinSpace
// If we are already below the scaleMinSpace value we will scale up
var length = Chartist.projectLength(axisLength, bounds.step, bounds),
scaleUp = length < scaleMinSpace;
while (true) {
if (scaleUp && Chartist.projectLength(axisLength, bounds.step, bounds) <= scaleMinSpace) {
bounds.step *= 2;
} else if (!scaleUp && Chartist.projectLength(axisLength, bounds.step / 2, bounds) >= scaleMinSpace) {
bounds.step /= 2;
} else {
break;
}
}
// Narrow min and max based on new step
newMin = bounds.min;
newMax = bounds.max;
for (i = bounds.min; i <= bounds.max; i += bounds.step) {
if (i + bounds.step < bounds.low) {
newMin += bounds.step;
}
if (i - bounds.step >= bounds.high) {
newMax -= bounds.step;
}
}
bounds.min = newMin;
bounds.max = newMax;
bounds.range = bounds.max - bounds.min;
bounds.values = [];
for (i = bounds.min; i <= bounds.max; i += bounds.step) {
bounds.values.push(Chartist.roundWithPrecision(i));
}
return bounds;
};
Calculate and retrieve all the bounds for the chart and return them in one array
Parameters
axisLength ( Number )highLow ( Object )scaleMinSpace ( Number )referenceValue ( Number )Returns
Object )method Chartist.polarToCartesian()
Chartist.polarToCartesian = function (centerX, centerY, radius, angleInDegrees) {
var angleInRadians = (angleInDegrees - 90) * Math.PI / 180.0;
return {
x: centerX + (radius * Math.cos(angleInRadians)),
y: centerY + (radius * Math.sin(angleInRadians))
};
};
Calculate cartesian coordinates of polar coordinates
Parameters
centerX ( Number )centerY ( Number )radius ( Number )angleInDegrees ( Number )Returns
Number )method Chartist.createChartRect()
Chartist.createChartRect = function (svg, options, fallbackPadding) {
var yOffset = options.axisY ? options.axisY.offset || 0 : 0,
xOffset = options.axisX ? options.axisX.offset || 0 : 0,
w = Chartist.stripUnit(options.width) || svg.width(),
h = Chartist.stripUnit(options.height) || svg.height(),
normalizedPadding = Chartist.normalizePadding(options.chartPadding, fallbackPadding);
return {
x1: normalizedPadding.left + yOffset,
y1: Math.max(h - normalizedPadding.bottom - xOffset, normalizedPadding.bottom),
x2: Math.max(w - normalizedPadding.right, normalizedPadding.right + yOffset),
y2: normalizedPadding.top,
width: function () {
return this.x2 - this.x1;
},
height: function () {
return this.y1 - this.y2;
}
};
};
Initialize chart drawing rectangle (area where chart is drawn) x1,y1 = bottom left / x2,y2 = top right
Parameters
svg ( Object )options ( Object )[fallbackPadding] ( Number )Returns
Object )method Chartist.createGrid()
Chartist.createGrid = function(projectedValue, index, axis, offset, length, group, classes, eventEmitter) {
var positionalData = {};
positionalData[axis.units.pos + '1'] = projectedValue.pos;
positionalData[axis.units.pos + '2'] = projectedValue.pos;
positionalData[axis.counterUnits.pos + '1'] = offset;
positionalData[axis.counterUnits.pos + '2'] = offset + length;
var gridElement = group.elem('line', positionalData, classes.join(' '));
// Event for grid draw
eventEmitter.emit('draw',
Chartist.extend({
type: 'grid',
axis: axis.units.pos,
index: index,
group: group,
element: gridElement
}, positionalData)
);
};
Creates a grid line based on a projected value.
Parameters
( projectedValue ) ( index ) ( axis ) ( offset ) ( length ) ( group ) ( classes ) ( eventEmitter )method Chartist.createLabel()
Chartist.createLabel = function(projectedValue, index, labels, axis, axisOffset, labelOffset, group, classes, useForeignObject, eventEmitter) {
var labelElement,
positionalData = {};
positionalData[axis.units.pos] = projectedValue.pos + labelOffset[axis.units.pos];
positionalData[axis.counterUnits.pos] = labelOffset[axis.counterUnits.pos];
positionalData[axis.units.len] = projectedValue.len;
positionalData[axis.counterUnits.len] = axisOffset;
if(useForeignObject) {
var content = '<span class="' + classes.join(' ') + '">' + labels[index] + '</span>';
labelElement = group.foreignObject(content, Chartist.extend({
style: 'overflow: visible;'
}, positionalData));
} else {
labelElement = group.elem('text', positionalData, classes.join(' ')).text(labels[index]);
}
eventEmitter.emit('draw', Chartist.extend({
type: 'label',
axis: axis,
index: index,
group: group,
element: labelElement,
text: labels[index]
}, positionalData));
};
Creates a label based on a projected value and an axis.
Parameters
( projectedValue ) ( index ) ( labels ) ( axis ) ( axisOffset ) ( labelOffset ) ( group ) ( classes ) ( useForeignObject ) ( eventEmitter )method Chartist.createAxis()
Chartist.createAxis = function(axis, data, chartRect, gridGroup, labelGroup, useForeignObject, options, eventEmitter) {
var axisOptions = options['axis' + axis.units.pos.toUpperCase()],
projectedValues = data.map(axis.projectValue.bind(axis)).map(axis.transform),
labelValues = data.map(axisOptions.labelInterpolationFnc);
projectedValues.forEach(function(projectedValue, index) {
// Skip grid lines and labels where interpolated label values are falsey (execpt for 0)
if(!labelValues[index] && labelValues[index] !== 0) {
return;
}
if(axisOptions.showGrid) {
Chartist.createGrid(projectedValue, index, axis, axis.gridOffset, chartRect[axis.counterUnits.len](), gridGroup, [
options.classNames.grid,
options.classNames[axis.units.dir]
], eventEmitter);
}
if(axisOptions.showLabel) {
Chartist.createLabel(projectedValue, index, labelValues, axis, axisOptions.offset, axis.labelOffset, labelGroup, [
options.classNames.label,
options.classNames[axis.units.dir]
], useForeignObject, eventEmitter);
}
});
};
This function creates a whole axis with its grid lines and labels based on an axis model and a chartRect.
Parameters
( axis ) ( data ) ( chartRect ) ( gridGroup ) ( labelGroup ) ( useForeignObject ) ( options ) ( eventEmitter )method Chartist.optionsProvider()
Chartist.optionsProvider = function (options, responsiveOptions, eventEmitter) {
var baseOptions = Chartist.extend({}, options),
currentOptions,
mediaQueryListeners = [],
i;
function updateCurrentOptions(preventChangedEvent) {
var previousOptions = currentOptions;
currentOptions = Chartist.extend({}, baseOptions);
if (responsiveOptions) {
for (i = 0; i < responsiveOptions.length; i++) {
var mql = window.matchMedia(responsiveOptions[i][0]);
if (mql.matches) {
currentOptions = Chartist.extend(currentOptions, responsiveOptions[i][1]);
}
}
}
if(eventEmitter && !preventChangedEvent) {
eventEmitter.emit('optionsChanged', {
previousOptions: previousOptions,
currentOptions: currentOptions
});
}
}
function removeMediaQueryListeners() {
mediaQueryListeners.forEach(function(mql) {
mql.removeListener(updateCurrentOptions);
});
}
if (!window.matchMedia) {
throw 'window.matchMedia not found! Make sure you\'re using a polyfill.';
} else if (responsiveOptions) {
for (i = 0; i < responsiveOptions.length; i++) {
var mql = window.matchMedia(responsiveOptions[i][0]);
mql.addListener(updateCurrentOptions);
mediaQueryListeners.push(mql);
}
}
// Execute initially so we get the correct options
updateCurrentOptions(true);
return {
get currentOptions() {
return Chartist.extend({}, currentOptions);
},
removeMediaQueryListeners: removeMediaQueryListeners
};
};
}(window, document, Chartist));
Provides options handling functionality with callback for options changes triggered by responsive options and media query matches
Parameters
options ( Object )responsiveOptions ( Array )eventEmitter ( Object )Returns
Object )event.js
Module Chartist.Event
A very basic event module that helps to generate and catch events.
function addEventHandler()
function addEventHandler(event, handler) {
handlers[event] = handlers[event] || [];
handlers[event].push(handler);
}
Add an event handler for a specific event
Parameters
event ( String )handler ( Function )function removeEventHandler()
function removeEventHandler(event, handler) {
// Only do something if there are event handlers with this name existing
if(handlers[event]) {
// If handler is set we will look for a specific handler and only remove this
if(handler) {
handlers[event].splice(handlers[event].indexOf(handler), 1);
if(handlers[event].length === 0) {
delete handlers[event];
}
} else {
// If no handler is specified we remove all handlers for this event
delete handlers[event];
}
}
}
Remove an event handler of a specific event name or remove all event handlers for a specific event.
Parameters
event ( String )[handler] ( Function )function emit()
function emit(event, data) {
// Only do something if there are event handlers with this name existing
if(handlers[event]) {
handlers[event].forEach(function(handler) {
handler(data);
});
}
// Emit event to star event handlers
if(handlers['*']) {
handlers['*'].forEach(function(starHandler) {
starHandler(event, data);
});
}
}
return {
addEventHandler: addEventHandler,
removeEventHandler: removeEventHandler,
emit: emit
};
};
}(window, document, Chartist));
Use this function to emit an event. All handlers that are listening for this event will be triggered with the data parameter.
Parameters
event ( String )data ( * )interpolation.js
Module Chartist.Interpolation
Chartist path interpolation functions.
method Chartist.Interpolation.none()
Chartist.Interpolation.none = function() {
return function cardinal(pathCoordinates) {
var path = new Chartist.Svg.Path().move(pathCoordinates[0], pathCoordinates[1]);
for(var i = 3; i < pathCoordinates.length; i += 2) {
path.line(pathCoordinates[i - 1], pathCoordinates[i]);
}
return path;
};
};
This interpolation function does not smooth the path and the result is only containing lines and no curves.
Returns
Function )method Chartist.Interpolation.simple()
Chartist.Interpolation.simple = function(options) {
var defaultOptions = {
divisor: 2
};
options = Chartist.extend({}, defaultOptions, options);
var d = 1 / Math.max(1, options.divisor);
return function simple(pathCoordinates) {
var path = new Chartist.Svg.Path().move(pathCoordinates[0], pathCoordinates[1]);
for(var i = 2; i < pathCoordinates.length; i += 2) {
var prevX = pathCoordinates[i - 2],
prevY = pathCoordinates[i - 1],
currX = pathCoordinates[i],
currY = pathCoordinates[i + 1],
length = (currX - prevX) * d;
path.curve(
prevX + length,
prevY,
currX - length,
currY,
currX,
currY
);
}
return path;
};
};
Simple smoothing creates horizontal handles that are positioned with a fraction of the length between two data points. You can use the divisor option to specify the amount of smoothing.
Parameters
options ( Object )Returns
Function )Examples
var chart = new Chartist.Line('.ct-chart', {
labels: [1, 2, 3, 4, 5],
series: [[1, 2, 8, 1, 7]]
}, {
lineSmooth: Chartist.Interpolation.simple({
divisor: 2
})
});
method Chartist.Interpolation.cardinal()
Chartist.Interpolation.cardinal = function(options) {
var defaultOptions = {
tension: 1
};
options = Chartist.extend({}, defaultOptions, options);
var t = Math.min(1, Math.max(0, options.tension)),
c = 1 - t;
return function cardinal(pathCoordinates) {
// If less than two points we need to fallback to no smoothing
if(pathCoordinates.length <= 4) {
return Chartist.Interpolation.none()(pathCoordinates);
}
var path = new Chartist.Svg.Path().move(pathCoordinates[0], pathCoordinates[1]),
z;
for (var i = 0, iLen = pathCoordinates.length; iLen - 2 * !z > i; i += 2) {
var p = [
{x: +pathCoordinates[i - 2], y: +pathCoordinates[i - 1]},
{x: +pathCoordinates[i], y: +pathCoordinates[i + 1]},
{x: +pathCoordinates[i + 2], y: +pathCoordinates[i + 3]},
{x: +pathCoordinates[i + 4], y: +pathCoordinates[i + 5]}
];
if (z) {
if (!i) {
p[0] = {x: +pathCoordinates[iLen - 2], y: +pathCoordinates[iLen - 1]};
} else if (iLen - 4 === i) {
p[3] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
} else if (iLen - 2 === i) {
p[2] = {x: +pathCoordinates[0], y: +pathCoordinates[1]};
p[3] = {x: +pathCoordinates[2], y: +pathCoordinates[3]};
}
} else {
if (iLen - 4 === i) {
p[3] = p[2];
} else if (!i) {
p[0] = {x: +pathCoordinates[i], y: +pathCoordinates[i + 1]};
}
}
path.curve(
(t * (-p[0].x + 6 * p[1].x + p[2].x) / 6) + (c * p[2].x),
(t * (-p[0].y + 6 * p[1].y + p[2].y) / 6) + (c * p[2].y),
(t * (p[1].x + 6 * p[2].x - p[3].x) / 6) + (c * p[2].x),
(t * (p[1].y + 6 * p[2].y - p[3].y) / 6) + (c * p[2].y),
p[2].x,
p[2].y
);
}
return path;
};
};
}(window, document, Chartist));
Cardinal / Catmull-Rome spline interpolation is the default smoothing function in Chartist. It produces nice results where the splines will always meet the points. It produces some artifacts though when data values are increased or decreased rapidly. The line may not follow a very accurate path and if the line should be accurate this smoothing function does not produce the best results.
Parameters
options ( Object )Returns
Function )Examples
var chart = new Chartist.Line('.ct-chart', {
labels: [1, 2, 3, 4, 5],
series: [[1, 2, 8, 1, 7]]
}, {
lineSmooth: Chartist.Interpolation.cardinal({
tension: 1
})
});
svg-path.js
Module Chartist.Svg.Path
Chartist SVG path module for SVG path description creation and modification.
declaration elementDescriptions
var elementDescriptions = {
m: ['x', 'y'],
l: ['x', 'y'],
c: ['x1', 'y1', 'x2', 'y2', 'x', 'y']
};
Contains the descriptors of supported element types in a SVG path. Currently only move, line and curve are supported.
declaration defaultOptions
var defaultOptions = {
// The accuracy in digit count after the decimal point. This will be used to round numbers in the SVG path. If this option is set to false then no rounding will be performed.
accuracy: 3
};
function element(command, params, pathElements, pos, relative) {
pathElements.splice(pos, 0, Chartist.extend({
command: relative ? command.toLowerCase() : command.toUpperCase()
}, params));
}
function forEachParam(pathElements, cb) {
pathElements.forEach(function(pathElement, pathElementIndex) {
elementDescriptions[pathElement.command.toLowerCase()].forEach(function(paramName, paramIndex) {
cb(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
});
});
}
Default options for newly created SVG path objects.
constructor SvgPath()
function SvgPath(close, options) {
this.pathElements = [];
this.pos = 0;
this.close = close;
this.options = Chartist.extend({}, defaultOptions, options);
}
Used to construct a new path object.
Parameters
close ( Boolean )options ( Object )function position()
function position(pos) {
if(pos !== undefined) {
this.pos = Math.max(0, Math.min(this.pathElements.length, pos));
return this;
} else {
return this.pos;
}
}
Gets or sets the current position (cursor) inside of the path. You can move around the cursor freely but limited to 0 or the count of existing elements. All modifications with element functions will insert new elements at the position of this cursor.
Parameters
[position] ( Number )Returns
Chartist.Svg.Path Number )function remove()
function remove(count) {
this.pathElements.splice(this.pos, count);
return this;
}
Removes elements from the path starting at the current position.
Parameters
count ( Number )Returns
Chartist.Svg.Path )function move()
function move(x, y, relative) {
element('M', {
x: +x,
y: +y
}, this.pathElements, this.pos++, relative);
return this;
}
Use this function to add a new move SVG path element.
Parameters
x ( Number )y ( Number )relative ( Boolean )Returns
Chartist.Svg.Path )function line()
function line(x, y, relative) {
element('L', {
x: +x,
y: +y
}, this.pathElements, this.pos++, relative);
return this;
}
Use this function to add a new line SVG path element.
Parameters
x ( Number )y ( Number )relative ( Boolean )Returns
Chartist.Svg.Path )function curve()
function curve(x1, y1, x2, y2, x, y, relative) {
element('C', {
x1: +x1,
y1: +y1,
x2: +x2,
y2: +y2,
x: +x,
y: +y
}, this.pathElements, this.pos++, relative);
return this;
}
Use this function to add a new curve SVG path element.
Parameters
x1 ( Number )y1 ( Number )x2 ( Number )y2 ( Number )x ( Number )y ( Number )relative ( Boolean )Returns
Chartist.Svg.Path )function parse()
function parse(path) {
// Parsing the SVG path string into an array of arrays [['M', '10', '10'], ['L', '100', '100']]
var chunks = path.replace(/([A-Za-z])([0-9])/g, '$1 $2')
.replace(/([0-9])([A-Za-z])/g, '$1 $2')
.split(/[\s,]+/)
.reduce(function(result, element) {
if(element.match(/[A-Za-z]/)) {
result.push([]);
}
result[result.length - 1].push(element);
return result;
}, []);
// If this is a closed path we remove the Z at the end because this is determined by the close option
if(chunks[chunks.length - 1][0].toUpperCase() === 'Z') {
chunks.pop();
}
// Using svgPathElementDescriptions to map raw path arrays into objects that contain the command and the parameters
// For example {command: 'M', x: '10', y: '10'}
var elements = chunks.map(function(chunk) {
var command = chunk.shift(),
description = elementDescriptions[command.toLowerCase()];
return Chartist.extend({
command: command
}, description.reduce(function(result, paramName, index) {
result[paramName] = +chunk[index];
return result;
}, {}));
});
// Preparing a splice call with the elements array as var arg params and insert the parsed elements at the current position
var spliceArgs = [this.pos, 0];
Array.prototype.push.apply(spliceArgs, elements);
Array.prototype.splice.apply(this.pathElements, spliceArgs);
// Increase the internal position by the element count
this.pos += elements.length;
return this;
}
Parses an SVG path seen in the d attribute of path elements, and inserts the parsed elements into the existing path object at the current cursor position. Any closing path indicators (Z at the end of the path) will be ignored by the parser as this is provided by the close option in the options of the path object.
Parameters
path ( String )Returns
Chartist.Svg.Path )function stringify()
function stringify() {
var accuracyMultiplier = Math.pow(10, this.options.accuracy);
return this.pathElements.reduce(function(path, pathElement) {
var params = elementDescriptions[pathElement.command.toLowerCase()].map(function(paramName) {
return this.options.accuracy ?
(Math.round(pathElement[paramName] * accuracyMultiplier) / accuracyMultiplier) :
pathElement[paramName];
}.bind(this));
return path + pathElement.command + params.join(',');
}.bind(this), '') + (this.close ? 'Z' : '');
}
This function renders to current SVG path object into a final SVG string that can be used in the d attribute of SVG path elements. It uses the accuracy option to round big decimals. If the close parameter was set in the constructor of this path object then a path closing Z will be appended to the output string.
Returns
String )function scale()
function scale(x, y) {
forEachParam(this.pathElements, function(pathElement, paramName) {
pathElement[paramName] *= paramName[0] === 'x' ? x : y;
});
return this;
}
Scales all elements in the current SVG path object. There is an individual parameter for each coordinate. Scaling will also be done for control points of curves, affecting the given coordinate.
Parameters
x ( Number )y ( Number )Returns
Chartist.Svg.Path )function translate()
function translate(x, y) {
forEachParam(this.pathElements, function(pathElement, paramName) {
pathElement[paramName] += paramName[0] === 'x' ? x : y;
});
return this;
}
Translates all elements in the current SVG path object. The translation is relative and there is an individual parameter for each coordinate. Translation will also be done for control points of curves, affecting the given coordinate.
Parameters
x ( Number )y ( Number )Returns
Chartist.Svg.Path )function transform()
function transform(transformFnc) {
forEachParam(this.pathElements, function(pathElement, paramName, pathElementIndex, paramIndex, pathElements) {
var transformed = transformFnc(pathElement, paramName, pathElementIndex, paramIndex, pathElements);
if(transformed || transformed === 0) {
pathElement[paramName] = transformed;
}
});
return this;
}
This function will run over all existing path elements and then loop over their attributes. The callback function will be called for every path element attribute that exists in the current path.
The method signature of the callback function looks like this:
function(pathElement, paramName, pathElementIndex, paramIndex, pathElements)
If something else than undefined is returned by the callback function, this value will be used to replace the old value. This allows you to build custom transformations of path objects that can't be achieved using the basic transformation functions scale and translate.
Parameters
transformFnc ( Function )Returns
Chartist.Svg.Path )function clone()
function clone() {
var c = new Chartist.Svg.Path(this.close);
c.pos = this.pos;
c.pathElements = this.pathElements.slice().map(function cloneElements(pathElement) {
return Chartist.extend({}, pathElement);
});
c.options = Chartist.extend({}, this.options);
return c;
}
Chartist.Svg.Path = Chartist.Class.extend({
constructor: SvgPath,
position: position,
remove: remove,
move: move,
line: line,
curve: curve,
scale: scale,
translate: translate,
transform: transform,
parse: parse,
stringify: stringify,
clone: clone
});
Chartist.Svg.Path.elementDescriptions = elementDescriptions;
}(window, document, Chartist));
This function clones a whole path object with all its properties. This is a deep clone and path element objects will also be cloned.
Returns
Chartist.Svg.Path )svg.js
Module Chartist.Svg
Chartist SVG module for simple SVG DOM abstraction
constructor Svg()
function Svg(name, attributes, className, parent, insertFirst) {
// If Svg is getting called with an SVG element we just return the wrapper
if(name instanceof SVGElement) {
this._node = name;
} else {
this._node = document.createElementNS(svgNs, name);
// If this is an SVG element created then custom namespace
if(name === 'svg') {
this._node.setAttributeNS(xmlNs, Chartist.xmlNs.qualifiedName, Chartist.xmlNs.uri);
}
if(attributes) {
this.attr(attributes);
}
if(className) {
this.addClass(className);
}
if(parent) {
if (insertFirst && parent._node.firstChild) {
parent._node.insertBefore(this._node, parent._node.firstChild);
} else {
parent._node.appendChild(this._node);
}
}
}
}
Chartist.Svg creates a new SVG object wrapper with a starting element. You can use the wrapper to fluently create sub-elements and modify them.
Parameters
name ( String SVGElement )attributes ( Object )className ( String )parent ( Object )insertFirst ( Boolean )function attr()
function attr(attributes, ns) {
if(typeof attributes === 'string') {
if(ns) {
return this._node.getAttributeNS(ns, attributes);
} else {
return this._node.getAttribute(attributes);
}
}
Object.keys(attributes).forEach(function(key) {
// If the attribute value is undefined we can skip this one
if(attributes[key] === undefined) {
return;
}
if(ns) {
this._node.setAttributeNS(ns, [Chartist.xmlNs.prefix, ':', key].join(''), attributes[key]);
} else {
this._node.setAttribute(key, attributes[key]);
}
}.bind(this));
return this;
}
Set attributes on the current SVG element of the wrapper you're currently working on.
Parameters
attributes ( Object String )ns ( String )Returns
Object String )function elem()
function elem(name, attributes, className, insertFirst) {
return new Chartist.Svg(name, attributes, className, this, insertFirst);
}
Create a new SVG element whose wrapper object will be selected for further operations. This way you can also create nested groups easily.
Parameters
name ( String )[attributes] ( Object )[className] ( String )[insertFirst] ( Boolean )Returns
Chartist.Svg )function foreignObject()
function foreignObject(content, attributes, className, insertFirst) {
// If content is string then we convert it to DOM
// TODO: Handle case where content is not a string nor a DOM Node
if(typeof content === 'string') {
var container = document.createElement('div');
container.innerHTML = content;
content = container.firstChild;
}
// Adding namespace to content element
content.setAttribute('xmlns', xhtmlNs);
// Creating the foreignObject without required extension attribute (as described here
// http://www.w3.org/TR/SVG/extend.html#ForeignObjectElement)
var fnObj = this.elem('foreignObject', attributes, className, insertFirst);
// Add content to foreignObjectElement
fnObj._node.appendChild(content);
return fnObj;
}
This method creates a foreignObject (see https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject) that allows to embed HTML content into a SVG graphic. With the help of foreignObjects you can enable the usage of regular HTML elements inside of SVG where they are subject for SVG positioning and transformation but the Browser will use the HTML rendering capabilities for the containing DOM.
Parameters
content ( Node String )[attributes] ( String )[className] ( String )[insertFirst] ( Boolean )Returns
Chartist.Svg )function text()
function text(t) {
this._node.appendChild(document.createTextNode(t));
return this;
}
This method adds a new text element to the current Chartist.Svg wrapper.
Parameters
t ( String )Returns
Chartist.Svg )function empty()
function empty() {
while (this._node.firstChild) {
this._node.removeChild(this._node.firstChild);
}
return this;
}
This method will clear all child nodes of the current wrapper object.
Returns
Chartist.Svg )function remove()
function remove() {
this._node.parentNode.removeChild(this._node);
return this.parent();
}
This method will cause the current wrapper to remove itself from its parent wrapper. Use this method if you'd like to get rid of an element in a given DOM structure.
Returns
Chartist.Svg )function replace()
function replace(newElement) {
this._node.parentNode.replaceChild(newElement._node, this._node);
return newElement;
}
This method will replace the element with a new element that can be created outside of the current DOM.
Parameters
newElement ( Chartist.Svg )Returns
Chartist.Svg )function append()
function append(element, insertFirst) {
if(insertFirst && this._node.firstChild) {
this._node.insertBefore(element._node, this._node.firstChild);
} else {
this._node.appendChild(element._node);
}
return this;
}
This method will append an element to the current element as a child.
Parameters
element ( Chartist.Svg )[insertFirst] ( Boolean )Returns
Chartist.Svg )function classes()
function classes() {
return this._node.getAttribute('class') ? this._node.getAttribute('class').trim().split(/\s+/) : [];
}
Returns an array of class names that are attached to the current wrapper element. This method can not be chained further.
Returns
Array )function addClass()
function addClass(names) {
this._node.setAttribute('class',
this.classes(this._node)
.concat(names.trim().split(/\s+/))
.filter(function(elem, pos, self) {
return self.indexOf(elem) === pos;
}).join(' ')
);
return this;
}
Adds one or a space separated list of classes to the current element and ensures the classes are only existing once.
Parameters
names ( String )Returns
Chartist.Svg )function removeClass()
function removeClass(names) {
var removedClasses = names.trim().split(/\s+/);
this._node.setAttribute('class', this.classes(this._node).filter(function(name) {
return removedClasses.indexOf(name) === -1;
}).join(' '));
return this;
}
Removes one or a space separated list of classes from the current element.
Parameters
names ( String )Returns
Chartist.Svg )function removeAllClasses()
function removeAllClasses() {
this._node.setAttribute('class', '');
return this;
}
Removes all classes from the current element.
Returns
Chartist.Svg )function height()
function height() {
return this._node.clientHeight || Math.round(this._node.getBBox().height) || this._node.parentNode.clientHeight;
}
Get element height with fallback to svg BoundingBox or parent container dimensions:
See bugzilla.mozilla.org
Returns
Number )function animate()
function animate(animations, guided, eventEmitter) {
if(guided === undefined) {
guided = true;
}
Object.keys(animations).forEach(function createAnimateForAttributes(attribute) {
function createAnimate(animationDefinition, guided) {
var attributeProperties = {},
animate,
timeout,
easing;
// Check if an easing is specified in the definition object and delete it from the object as it will not
// be part of the animate element attributes.
if(animationDefinition.easing) {
// If already an easing Bézier curve array we take it or we lookup a easing array in the Easing object
easing = animationDefinition.easing instanceof Array ?
animationDefinition.easing :
Chartist.Svg.Easing[animationDefinition.easing];
delete animationDefinition.easing;
}
// If numeric dur or begin was provided we assume milli seconds
animationDefinition.begin = Chartist.ensureUnit(animationDefinition.begin, 'ms');
animationDefinition.dur = Chartist.ensureUnit(animationDefinition.dur, 'ms');
if(easing) {
animationDefinition.calcMode = 'spline';
animationDefinition.keySplines = easing.join(' ');
animationDefinition.keyTimes = '0;1';
}
// Adding "fill: freeze" if we are in guided mode and set initial attribute values
if(guided) {
animationDefinition.fill = 'freeze';
// Animated property on our element should already be set to the animation from value in guided mode
attributeProperties[attribute] = animationDefinition.from;
this.attr(attributeProperties);
// In guided mode we also set begin to indefinite so we can trigger the start manually and put the begin
// which needs to be in ms aside
timeout = Chartist.stripUnit(animationDefinition.begin || 0);
animationDefinition.begin = 'indefinite';
}
animate = this.elem('animate', Chartist.extend({
attributeName: attribute
}, animationDefinition));
if(guided) {
// If guided we take the value that was put aside in timeout and trigger the animation manually with a timeout
setTimeout(function() {
// If beginElement fails we set the animated attribute to the end position and remove the animate element
// This happens if the SMIL ElementTimeControl interface is not supported or any other problems occured in
// the browser. (Currently FF 34 does not support animate elements in foreignObjects)
try {
animate._node.beginElement();
} catch(err) {
// Set animated attribute to current animated value
attributeProperties[attribute] = animationDefinition.to;
this.attr(attributeProperties);
// Remove the animate element as it's no longer required
animate.remove();
}
}.bind(this), timeout);
}
if(eventEmitter) {
animate._node.addEventListener('beginEvent', function handleBeginEvent() {
eventEmitter.emit('animationBegin', {
element: this,
animate: animate._node,
params: animationDefinition
});
}.bind(this));
}
animate._node.addEventListener('endEvent', function handleEndEvent() {
if(eventEmitter) {
eventEmitter.emit('animationEnd', {
element: this,
animate: animate._node,
params: animationDefinition
});
}
if(guided) {
// Set animated attribute to current animated value
attributeProperties[attribute] = animationDefinition.to;
this.attr(attributeProperties);
// Remove the animate element as it's no longer required
animate.remove();
}
}.bind(this));
}
// If current attribute is an array of definition objects we create an animate for each and disable guided mode
if(animations[attribute] instanceof Array) {
animations[attribute].forEach(function(animationDefinition) {
createAnimate.bind(this)(animationDefinition, false);
}.bind(this));
} else {
createAnimate.bind(this)(animations[attribute], guided);
}
}.bind(this));
return this;
}
Chartist.Svg = Chartist.Class.extend({
constructor: Svg,
attr: attr,
elem: elem,
parent: parent,
root: root,
querySelector: querySelector,
querySelectorAll: querySelectorAll,
foreignObject: foreignObject,
text: text,
empty: empty,
remove: remove,
replace: replace,
append: append,
classes: classes,
addClass: addClass,
removeClass: removeClass,
removeAllClasses: removeAllClasses,
height: height,
width: width,
animate: animate
});
The animate function lets you animate the current element with SMIL animations. You can add animations for multiple attributes at the same time by using an animation definition object. This object should contain SMIL animation attributes. Please refer to http://www.w3.org/TR/SVG/animate.html for a detailed specification about the available animation attributes. Additionally an easing property can be passed in the animation definition object. This can be a string with a name of an easing function in Chartist.Svg.Easing or an array with four numbers specifying a cubic Bézier curve.
An animations object could look like this:
element.animate({
opacity: {
dur: 1000,
from: 0,
to: 1
},
x1: {
dur: '1000ms',
from: 100,
to: 200,
easing: 'easeOutQuart'
},
y1: {
dur: '2s',
from: 0,
to: 100
}
});
Automatic unit conversion
For the dur and the begin animate attribute you can also omit a unit by passing a number. The number will automatically be converted to milli seconds.
Guided mode
The default behavior of SMIL animations with offset using the begin attribute is that the attribute will keep it's original value until the animation starts. Mostly this behavior is not desired as you'd like to have your element attributes already initialized with the animation from value even before the animation starts. Also if you don't specify fill="freeze" on an animate element or if you delete the animation after it's done (which is done in guided mode) the attribute will switch back to the initial value. This behavior is also not desired when performing simple one-time animations. For one-time animations you'd want to trigger animations immediately instead of relative to the document begin time. That's why in guided mode Chartist.Svg will also use the begin property to schedule a timeout and manually start the animation after the timeout. If you're using multiple SMIL definition objects for an attribute (in an array), guided mode will be disabled for this attribute, even if you explicitly enabled it.
If guided mode is enabled the following behavior is added:
- Before the animation starts (even when delayed with
begin) the animated attribute will be set already to thefromvalue of the animation beginis explicitly set toindefiniteso it can be started manually without relying on document begin time (creation)- The animate element will be forced to use
fill="freeze" - The animation will be triggered with
beginElement()in a timeout wherebeginof the definition object is interpreted in milli seconds. If nobeginwas specified the timeout is triggered immediately. - After the animation the element attribute value will be set to the
tovalue of the animation - The animate element is deleted from the DOM
Parameters
animations ( Object )guided ( Boolean )eventEmitter ( Object )Returns
Chartist.Svg )method Chartist.Svg.isSupported()
Chartist.Svg.isSupported = function(feature) {
return document.implementation.hasFeature('www.http://w3.org/TR/SVG11/feature#' + feature, '1.1');
};
/**
* This Object contains some standard easing cubic bezier curves. Then can be used with their name in the `Chartist.Svg.animate`. You can also extend the list and use your own name in the `animate` function. Click the show code button to see the available bezier functions.
*
* @memberof Chartist.Svg
*/
var easingCubicBeziers = {
easeInSine: [0.47, 0, 0.745, 0.715],
easeOutSine: [0.39, 0.575, 0.565, 1],
easeInOutSine: [0.445, 0.05, 0.55, 0.95],
easeInQuad: [0.55, 0.085, 0.68, 0.53],
easeOutQuad: [0.25, 0.46, 0.45, 0.94],
easeInOutQuad: [0.455, 0.03, 0.515, 0.955],
easeInCubic: [0.55, 0.055, 0.675, 0.19],
easeOutCubic: [0.215, 0.61, 0.355, 1],
easeInOutCubic: [0.645, 0.045, 0.355, 1],
easeInQuart: [0.895, 0.03, 0.685, 0.22],
easeOutQuart: [0.165, 0.84, 0.44, 1],
easeInOutQuart: [0.77, 0, 0.175, 1],
easeInQuint: [0.755, 0.05, 0.855, 0.06],
easeOutQuint: [0.23, 1, 0.32, 1],
easeInOutQuint: [0.86, 0, 0.07, 1],
easeInExpo: [0.95, 0.05, 0.795, 0.035],
easeOutExpo: [0.19, 1, 0.22, 1],
easeInOutExpo: [1, 0, 0, 1],
easeInCirc: [0.6, 0.04, 0.98, 0.335],
easeOutCirc: [0.075, 0.82, 0.165, 1],
easeInOutCirc: [0.785, 0.135, 0.15, 0.86],
easeInBack: [0.6, -0.28, 0.735, 0.045],
easeOutBack: [0.175, 0.885, 0.32, 1.275],
easeInOutBack: [0.68, -0.55, 0.265, 1.55]
};
Chartist.Svg.Easing = easingCubicBeziers;
/**
* This helper class is to wrap multiple `Chartist.Svg` elements into a list where you can call the `Chartist.Svg` functions on all elements in the list with one call. This is helpful when you'd like to perform calls with `Chartist.Svg` on multiple elements.
* An instance of this class is also returned by `Chartist.Svg.querySelectorAll`.
*
* @memberof Chartist.Svg
* @param {Array<Node>|NodeList} nodeList An Array of SVG DOM nodes or a SVG DOM NodeList (as returned by document.querySelectorAll)
* @constructor
*/
function SvgList(nodeList) {
var list = this;
this.svgElements = [];
for(var i = 0; i < nodeList.length; i++) {
this.svgElements.push(new Chartist.Svg(nodeList[i]));
}
// Add delegation methods for Chartist.Svg
Object.keys(Chartist.Svg.prototype).filter(function(prototypeProperty) {
return ['constructor',
'parent',
'querySelector',
'querySelectorAll',
'replace',
'append',
'classes',
'height',
'width'].indexOf(prototypeProperty) === -1;
}).forEach(function(prototypeProperty) {
list[prototypeProperty] = function() {
var args = Array.prototype.slice.call(arguments, 0);
list.svgElements.forEach(function(element) {
Chartist.Svg.prototype[prototypeProperty].apply(element, args);
});
return list;
};
});
}
Chartist.Svg.List = Chartist.Class.extend({
constructor: SvgList
});
}(window, document, Chartist));
This method checks for support of a given SVG feature like Extensibility, SVG-animation or the like. Check http://www.w3.org/TR/SVG11/feature for a detailed list.
Parameters
feature ( String )Returns
Boolean )