Chartist.js, An Open-Source Library For Responsive Charts
- By Gion Kunz
- December 16th, 2014
- 0 Comments
The list of charting libraries for a web is already utterly long, and we competence ask yourself since we would need to make it any longer. Whenever we need to rise an application’s dashboard, hide some use statistics or simply daydream some data, we will find yourself looking for a charting library that fits your needs.
Chartist was grown for a really sold need: to emanate elementary manageable charts. While other charting libraries do a good pursuit of visualizing data, something is always blank to prove this elementary nonetheless perfectionist need.
In this article, we’ll uncover we how to use Chartist to emanate your possess pleasing manageable charts. You’ll learn some pivotal concepts of Chartist, how to simply extend it and also some modernized features, like manageable pattern overrides and a animation API.
Your Individual Setup
You can confederate a Chartist library in your plan in many ways. It’s permitted from Bower and NPM yet also directly from a calm smoothness network (CDN). It’s also unprotected as a CommonJS module, as an AMD procedure or usually in a tellurian window object. You can confirm on a best proceed to confederate a library according to your project’s setup.
Chartist now uses a Universal Module Definition2 wrapper, to prove a extended operation of use cases. Instead of regulating Chartist directly from a Chartist
namespace in a window object, we could use procedure loaders, like RequireJS, or gold your charts into your concentration with Browserify or webpack.
Bower
To exercise Chartist as a front-end dependency regulating Bower, simply govern a following authority in your project’s folder:
bower exercise chartist --save
NPM
If we cite NPM as a repository or if you’re regulating a CommonJS browser bundler like Browserify or webpack, afterwards you’ll wish to exercise Chartist regulating NPM:
npm exercise chartist --save
CDN
Another discerning proceed to get started with Chartist is to use a CDN. The folks during jsDelivr do a illusory pursuit of gripping a outrageous array of libraries adult to date with their tradition bucket balancing3, and they do it all for free. To use Chartist’s resources from a CDN, embody a following in your HTML:
script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"/script
link href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" type="text/css" /
Create Your First Chart
Once we have selected a routine that fits your needs, we can start crafting your initial chart. Over a march of this article, we’ll use JSBin4 to emanate a charts. JSBin is a good collaborative web growth debugging tool, and Chartist is permitted directly in a “Add library” menu. If you’d like to try out Chartist quickly, I’d suggest regulating JSBin.
Let’s start with a elementary line chart. For this, we’ll initial supplement a enclosure component to a body
with a category ct-chart
.
!DOCTYPE html
html
head
book src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"/script
couple href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" type="text/css" /
meta charset="utf-8"
titleChartist | Simple line chart/title
/head
body
div class="ct-chart"/div
/body
/html
Now we can initialize a line draft on a enclosure with usually a few lines of JavaScript. Let’s emanate 3 series, with 5 values each. We’ll also set a list of labels for a x-axis. As a second argument, a Chartist.Line
constructor accepts an options object. Here, we can mention a bound width
and height
for a chart.
new Chartist.Line('.ct-chart',
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [
[2, 3, 2, 4, 5],
[0, 2.5, 3, 2, 3],
[1, 2, 2.5, 3.5, 4]
]
,
width: 320,
height: 240
);
Edit on JSBin6
Responsive Containers With Intrinsic Ratios
In a instance above, we used a bound width
and height
for a chart. This is not always desired, and in manageable pattern we should keep a elements liquid and not consider in bound dimensions.
Chartist uses a possess classes to set containers with bound aspect ratios (intrinsic ratios). Usually, this is a technique practical to manageable videos and iframes, and it uses a singular ratio CSS trick7 to settle a bound ratio container. With a doing in Chartist8, we can even set a breadth of a enclosure while preserving a aspect ratio.
Let’s use one of a generated manageable enclosure classes in Chartist to stretch a chart. I’ve picked ct-golden-section
, yet we can select any from a list of generated enclosure classes9. When regulating a Sass chronicle of Chartist, we can also beget your possess fixed-aspect-ratio containers easily.
body
div class="ct-chart ct-golden-section"/div
/body
Because we are now naming a enclosure with a bound aspect ratio on a chart, we no longer need to rest on bound measure when initializing a chart. Let’s mislay a width
and height
in a configuration.
new Chartist.Line('.ct-chart',
labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'],
series: [
[2, 3, 2, 4, 5],
[0, 2.5, 3, 2, 3],
[1, 2, 2.5, 3.5, 4]
]
);
Edit on JSBin10
Now we have a draft that responds to changes in media. Try resizing a outlay row on JSBin to see how a draft adapts to changes in window size.
Advanced Configuration
One of Chartist’s core beliefs is a purify subdivision of concerns around customary web technologies. This includes requesting all appearance-related settings with CSS. Also, a array of settings concede we to control a duty of your chart. These settings are practical regulating JavaScript and can be upheld to your draft during initialization.
Let’s emanate a elementary bar draft that visualizes some information for weekdays.
new Chartist.Bar('.ct-chart',
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
series: [
[2, 8, 2, 4, 5, 8, 10],
[4, 5, 8, 2, 6, 3, 10]
]
,
seriesBarDistance: 30,
axisX:
showGrid: false
);
Edit on JSBin12
In a options, we can control a stretch of a bars and tell Chartist not to describe a grid on a x-axis. For a finish list of options, we can always revisit Chartist’s API documentation13.
By default, a labels on a x-axis are left-aligned. To make them center-aligned, we need to supplement a CSS style. We also wish to change a bar’s breadth to 20 pixels.
.ct-chart .ct-bar
stroke-width: 20px;
.ct-chart .ct-label.ct-horizontal
text-align: center;
Edit on JSBin14
Already, we’ve got a nice-looking bar draft for vast screens.
Responsive Configuration Override
The instance above works simply on desktop screens, yet not on inclination with parsimonious shade resolutions. The bars are too wide, a labels too vast and a names of a weekdays are combined in full. Also, a stretch of a bars needs to be adjusted.
Some of these changes can be finished in CSS by modifying a bar’s breadth in a media query. But how do we go about requesting opposite configurations in JavaScript? Chartist provides a resource for this purpose called manageable pattern override.
Let’s demeanour during a prior instance and rewrite it with a mobile-first approach. We’ll optimize a media queries for a calm we’re operative with, introducing a breakpoint during 300 pixels and another during 600 pixels.
.ct-chart .ct-label.ct-horizontal
text-align: center;
.ct-chart .ct-bar
stroke-width: 5px;
@media shade and (min-width: 300px)
.ct-chart .ct-bar
stroke-width: 10px;
@media shade and (min-width: 600px)
.ct-chart .ct-bar
stroke-width: 20px;
If we’d like to tailor a draft to a sold medium, we can use a manageable pattern overrides. We simply tell Chartist to get and overrule a pattern formed on a same media queries in a CSS. Chartist uses window.matchMedia
15 to exercise an estate in a settings identical to what CSS does with a styles.
The following instance uses labelInterpolationFnc
to pass a duty that enables us to introduce or even reinstate a label’s strange value for a given axis. This means we can control how a weekdays’ names are displayed on a x-axis.
new Chartist.Bar('.ct-chart',
labels: ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'],
series: [
[2, 8, 2, 4, 5, 8, 10],
[4, 5, 8, 2, 6, 3, 10]
]
,
seriesBarDistance: 6,
axisX:
showGrid: false,
// Only lapse initial minute of weekday names
labelInterpolationFnc: function(value)
lapse value[0];
, [
// Over 300px, we change a bar stretch and uncover a initial 3 letters of a weekdays
['screen and (min-width: 300px)',
seriesBarDistance: 15,
axisX:
labelInterpolationFnc: function(value)
lapse value.slice(0, 3);
],
// Over 600px, we boost a bar stretch one some-more time and uncover a full weekdays
['screen and (min-width: 600px)',
seriesBarDistance: 30,
axisX:
labelInterpolationFnc: function(value) lapse value;
]
]);
Edit on JSBin17
In a instance above, we can see how easy it is to emanate a draft that works on both mobile and desktop, while progressing a purify subdivision of concerns.
Styling SVG With CSS
Styling inline SVG with CSS is easy and fit since you’re means to reuse styles for opposite charts. You can embody CSS classes that conclude a demeanour and feel of your charts and that keep a proof distant from a appearance.
Here are some of a many useful CSS properties for styling inline SVG:
fill
Sets a tone of a shape’s fill. You competence use RGBa.stroke
Sets a tone of a outline around your shape.stroke-width
Sets a breadth of an outline.stroke-dasharray
Specifies a dashed cadence for an outline.stroke-linecap
Sets a line-cap cadence for a outline of a shape. This can be set toround
,butt
orsquare
.
Check a SVG 1.1 selection for a finish list of SVG styling properties18.
Let’s request a new styling skills and emanate a line draft with 3 opposite looking series. We’ll use all of a above styling properties to give a draft a singular look.
.ct-chart .ct-label.ct-vertical,
.ct-chart .ct-label.ct-horizontal
color: rgba(255, 255, 255, 0.5);
.ct-chart .ct-grid.ct-vertical,
.ct-chart .ct-grid.ct-horizontal
stroke: rgba(255, 255, 255, 0.1);
shape-rendering: crispEdges;
.ct-chart .ct-series.ct-series-a .ct-line
stroke:
stroke-width: 10px;
stroke-linecap: round;
.ct-chart .ct-series.ct-series-b .ct-line
stroke:
stroke-width: 2px;
stroke-dasharray: 5px 2px;
.ct-chart .ct-series.ct-series-c .ct-line
stroke:
stroke-width: 3px;
stroke-linecap: round;
stroke-dasharray: 30px 5px;
Edit on JSBin20
If we play around with this instance a bit, you’ll fast see how easy it is to character SVG with CSS. Also, we competence have beheld a shape-rendering: crispEdges
character on a grid lines. While we haven’t enclosed a shape-rendering
skill in a list of useful styling properties, you’ll find it utterly permitted in some situations. It allows we to give a browser some hints on how to describe SVG. The values auto
, optimizeSpeed
, crispEdges
and geometricPrecision
are upheld by a specification. Intended for opening control, this skill is also permitted for digest certain shapes yet anti-aliasing. In some charts, including a instance above, origination a grid lines demeanour really frail with a crispEdges
value has a really good effect.
CSS Animation Craziness
I’m a outrageous fan of animation… well, as prolonged as it supports a calm and conveys information to a user. It can meant a disproportion between a UX personification simply and not. Google’s component design21 is a good instance of organic animation design. However, for this article, we will not concentration on organic animation, yet instead go a bit crazy with a possibilities during a disposal. Browser support for animation of SVG properties is flattering fast now, and we can even spur a stroke-dasharray
and stroke-dashoffset
properties. Let’s raise a prior instance with some suggestive animation.
Simply by regulating some CSS3, we are means to emanate some crazy animations in a chart.
@keyframes width-pulse
0%
stroke-width: 6px
50%
stroke-width: 14px;
100%
stroke-width: 6px;
@keyframes dashoffset-seven
0%
stroke-dashoffset: 7px;
100%
stroke-dashoffset: 0px;
@keyframes dasharray-craziness
0%
stroke-dasharray: 7px 2px;
80%
stroke-dasharray: 7px 100px;
stroke-width: 10px
100%
stroke-dasharray: 7px 2px;
.ct-chart .ct-label.ct-vertical,
.ct-chart .ct-label.ct-horizontal
color: rgba(255, 255, 255, 0.5);
.ct-chart .ct-grid.ct-vertical,
.ct-chart .ct-grid.ct-horizontal
stroke: rgba(255, 255, 255, 0.1);
stroke-dasharray: 2px;
shape-rendering: crispEdges;
.ct-chart .ct-series.ct-series-a .ct-line
stroke:
stroke-width: 10px;
stroke-linecap: round;
animation: width-pulse 2s infinite;
.ct-chart .ct-series.ct-series-b .ct-line
stroke:
stroke-width: 2px;
stroke-dasharray: 5px 2px;
animation: dashoffset-seven 200ms gigantic linear;
.ct-chart .ct-series.ct-series-c .ct-line
stroke:
stroke-width: 3px;
stroke-linecap: round;
stroke-dasharray: 30px 5px;
animation: dasharray-craziness 10s gigantic linear;
Edit on JSBin23
As we can see, styling and animating SVG regulating CSS is a lot of fun. If you’d like some-more information, we suggest a essay by Sara Soueidan “Styling and Animating SVGs With CSS24.”
Animating With SMIL
CSS animation is a good proceed to inject some life into a chart. There are some things we can’t spur with CSS, though. If we wish to spur particular parameters of an SVG component to morph a shape, afterwards we would use a Chartist.Svg
APIs to conveniently emanate SMIL animations.
SMIL is powerful, yet a declarative API, that uses animate
elements, can be treacherous in a complexity. Chartist offers a high-level API that enables we to simply take advantage of SMIL animations in your charts.
The idea of Chartist is to facilitate a doing of SMIL while preserving a semantics specified by a W3C. Chartist uses a possess SVG strategy library, that is permitted by Chartist.Svg
. Similar to jQuery, it provides a coupling intent around genuine SVG DOM nodes, giving we some accessible methods to manipulate a underlying SVG. You can get a finish overview by browsing a Chartist.Svg
API documentation25.
To spur an SVG element, we initial need to obtain a coupling intent by flitting an SVG node to a Chartist.Svg
constructor.
var component = new Chartist.Svg(document.querySelector('#my-specific-svg-element'));
You can afterwards call a animate
duty on your wrapped component with an animation clarification object:
element.animate(
opacity:
dur: 1000,
from: 0,
to: 1
,
x1:
dur: '1000ms',
from: 100,
to: 200,
easing: 'easeOutQuart'
,
y1:
begin: 1000,
dur: '2s',
from: 0,
to: 100
);
This will emanate 3 SMIL animate
elements, any of that contains a SMIL animation attributes specified in a clarification objects. The Chartist animation API has a few particularities. The begin
and dur
(i.e. duration) properties competence be specified as unitless numbers; Chartist will modify a numbers to milliseconds automatically. Chartist also supports an easing
skill in a animation clarification intent that is not directly upheld by SMIL. The easing
skill allows we to mention an easing duty from Chartist.Svg.Easing
, that will be translated to a SMIL interpolation function.
Chartist handles SMIL animations in a special guided mode by default. The guided mode includes a following behavior, that creates doing and optimization easier for immediately triggered animations:
- Before a animation starts (even when behind with
begin
), a charcterised charge will already be set to afrom
value of a animation. begin
is categorically set toindefinite
so that it can be started manually yet relying on a document’s start time (i.e. creation).- The
animate
component is forced to usefill="freeze"
. - The animation is triggered with
beginElement()
in a timeout, where a commencement of a clarification intent is interpreted in milliseconds. If no commencement is specified, afterwards a timeout is triggered immediately. - After a animation, a element’s charge value is set to a
to
value of a animation. - The
animate
component is afterwards deleted from a DOM.
You can also invalidate guided mode by flitting false
as a second evidence to a animate
function.
Animating Chart Elements Using a Event API
Chartist provides a few events that we can use to prevent a origination routine of charts. The draw
events of Chartist get triggered any time a draft component is combined in a DOM. Since we have a Chartist.Svg
coupling and all applicable information permitted in a eventuality callback, this creates it a ideal mark to supplement a animations.
This instance looks some-more like a confetti celebration than a chart, yet it should illustrate how easy it is to emanate tradition animations. The instance creates use of a Chartist eventuality API and adds animations to points in a line chart.
var seq = 0;
chart.on('created', function()
seq = 0;
);
chart.on('draw', function(data)
if(data.type === 'point')
seq++;
data.element.animate(
x1:
from: data.x - 50,
to: data.x,
begin: seq * 80,
dur: 800,
easing: Chartist.Svg.Easing.easeOutQuint
,
opacity:
from: 0,
to: 1,
begin: seq * 80,
dur: 300,
);
);
Edit on JSBin27
Extensibility
Because Chartist uses inline SVG in a DOM, fluctuating a core functionality is really easy. While SVG elements in a DOM have a same events as unchanging DOM elements, we can simply use a DOM library of your choice and supplement tradition functionality to your chart’s elements.
This instance shows we how to supplement a elementary tooltip to a draft regulating jQuery. When a user hovers over a information point, a tooltip should turn manifest and arrangement a information value.
var $tooltip = $('div class="tooltip tooltip-hidden"/div').appendTo($('.ct-chart'));
$(document).on('mouseenter', '.ct-point', function()
var seriesName = $(this).closest('.ct-series').attr('ct:series-name'),
value = $(this).attr('ct:value');
$tooltip.text(seriesName + ': ' + value);
$tooltip.removeClass('tooltip-hidden');
);
$(document).on('mouseleave', '.ct-point', function()
$tooltip.addClass('tooltip-hidden');
);
$(document).on('mousemove', '.ct-point', function(event)
$tooltip.css(
left: event.offsetX - $tooltip.width() / 2,
top: event.offsetY - $tooltip.height() - 20
);
);
Edit on JSBin29
The instance above uses unchanging DOM events to supplement a elementary tooltip. You competence have beheld a use of a ct:value
charge from a line chart’s indicate component and a ct:series-name
charge from a array group. Chartist has a possess XML namespace, that it uses to display some meta information to a SVG. This creates it easy to remove information from a DOM and use it for tradition functionality.
Extending a Drawing Pipeline
The eventuality complement of Chartist is absolute and is a good apparatus to extend your draft with tradition features. The following instance uses a draw
eventuality of a line draft to reinstate a tedious indicate elements with something smashing.
var smashingImgTag = 'img src="http://media.mediatemple.netdna-cdn.com/wp-content/themes/smashing-magazine/images/smashing-windows-icon-70-70.png" style="width: 40px; height: 40px" alt="Smashing Logo" /';
chart.on('draw', function(data)
if(data.type === 'point')
var smashingFoob = data.element.parent().foreignObject(smashingImgTag,
width: 40,
height: 40,
x: data.x - 20,
y: data.y - 20
);
data.element.replace(smashingFoob);
);
Edit in JSBin31
In a instance above, we’ve transposed any indicate component usually after it has been drawn (inserted in a DOM tree) with a foreignObject
that contains an image. A foreignObject
allows we to hide HTML elements in an SVG. The Chartist.Svg
API provides an easy and accessible proceed to emanate foreignObjects
. For sum on a Chartist.Svg
API, revisit a API documentation32.
Resources
- “API Documentation33,” Chartist
More information on how to use a library - “Examples34,” Chartist
Provides some instance charts where we can now formula on them online. - “Scalable Vector Graphics 1.1 (Second Edition)35,” W3C
The SVG specification - “SMIL 3.0 Animation36,” W3C
The SMIL specification - “foreignObject37,” Mozilla Developer Network
Contribute
We are constantly looking for people to get involved. If we have some gangling time and are meddlesome in contributing, greatfully squeeze an emanate to work on or open a new one.
(vf, al, il)
Footnotes
- 1 http://gionkunz.github.io/chartist-js/
- 2 https://github.com/umdjs/umd
- 3 https://hacks.mozilla.org/2014/11/jsdelivr-and-its-open-source-load-balancing-algorithm/
- 4 http://jsbin.com/
- 5 http://jsbin.com/qalewi
- 6 http://jsbin.com/qalewi/edit?js,output
- 7 http://alistapart.com/article/creating-intrinsic-ratios-for-video
- 8 https://github.com/gionkunz/chartist-js/blob/develop/src/styles/chartist.scss#L4-L30
- 9 http://gionkunz.github.io/chartist-js/getting-started.html#creating-a-chart-using-aspect-ratios
- 10 http://jsbin.com/quyamo/edit?js,output
- 11 http://jsbin.com/kebaye
- 12 http://jsbin.com/kebaye/edit?js,output
- 13 http://gionkunz.github.io/chartist-js/api-documentation.html
- 14 http://jsbin.com/kebaye/edit?css,output
- 15 https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia
- 16 http://jsbin.com/ciyunu
- 17 http://jsbin.com/ciyunu/edit?js,css,output
- 18 http://www.w3.org/TR/SVG/styling.html#SVGStylingProperties
- 19 http://jsbin.com/zoruko
- 20 http://jsbin.com/zoruko/edit?css,output
- 21 http://www.google.com/design/spec/animation/meaningful-transitions.html
- 22 http://jsbin.com/jovuh
- 23 http://jsbin.com/jovuh/edit?css,output
- 24 http://www.smashingmagazine.com/2014/11/03/styling-and-animating-svgs-with-css/
- 25 http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-svg
- 26 http://jsbin.com/zumubi
- 27 http://jsbin.com/zumubi/edit?js,output
- 28 http://jsbin.com/seruk
- 29 http://jsbin.com/seruk/edit?js,output
- 30 http://jsbin.com/nupexe
- 31 http://jsbin.com/nupexe/edit?js,output
- 32 http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-constructor-svg
- 33 http://gionkunz.github.io/chartist-js/api-documentation.html
- 34 http://gionkunz.github.io/chartist-js/examples.html
- 35 http://www.w3.org/TR/SVG/
- 36 http://www.w3.org/TR/SMIL3/smil-animation.html
- 37 https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject
↑ Back to topShare on Twitter
Chartist.js, An Open-Source Library For Responsive Charts
Nenhum comentário:
Postar um comentário