Menu Search
Jump to the content X X
Smashing Conf New York

We use ad-blockers as well, you know. We gotta keep those servers running though. Did you know that we publish useful books and run friendly conferences — crafted for pros like yourself? E.g. upcoming SmashingConf Barcelona, dedicated to smart front-end techniques and design patterns.

Chartist.js, An Open-Source Library For Responsive Charts

The list of charting libraries for the web is already quite long, and you might ask yourself why we would need to make it any longer. Whenever you need to develop an application’s dashboard, embed some usage statistics or simply visualize some data, you will find yourself looking for a charting library that fits your needs.

Chartist was developed for a very particular need: to create simple responsive charts. While other charting libraries do a great job of visualizing data, something is always missing to satisfy this simple yet demanding need.

In this article, we’ll show you how to use Chartist to create your own beautiful responsive charts. You’ll learn some key concepts of Chartist, how to easily extend it and also some advanced features, like responsive configuration overrides and the animation API.

Chartist guy pointing at a chart1

Chartist guy pointing at a chart

Your Individual Setup Link

You can integrate the Chartist library in your project in many ways. It’s available from Bower and NPM but also directly from a content delivery network (CDN). It’s also exposed as a CommonJS module, as an AMD module or just in the global window object. You can decide on the best way to integrate the library according to your project’s setup.

Chartist currently uses a Universal Module Definition2 wrapper, to satisfy a broad range of use cases. Instead of using Chartist directly from the Chartist namespace in the window object, you could use module loaders, like RequireJS, or bundle your charts into your application with Browserify or webpack.

Bower Link

To install Chartist as a front-end dependency using Bower, simply execute the following command in your project’s folder:

bower install chartist --save

NPM Link

If you prefer NPM as a repository or if you’re using a CommonJS browser bundler like Browserify or webpack, then you’ll want to install Chartist using NPM:

npm install chartist --save

CDN Link

Another quick way to get started with Chartist is to use a CDN. The folks at jsDelivr do a fantastic job of keeping a huge number of libraries up to date with their custom load balancing3, and they do it all for free. To use Chartist’s resources from a CDN, include the 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 Link

Once you have chosen the method that fits your needs, you can start crafting your first chart. Over the course of this article, we’ll use JSBin4 to create our charts. JSBin is a great collaborative web development debugging tool, and Chartist is available directly in the “Add library” menu. If you’d like to try out Chartist quickly, I’d recommend using JSBin.

Let’s start with a simple line chart. For this, we’ll first add a container element to our body with the class ct-chart.

Simple line chart with three series5

Simple line chart with three series
<!DOCTYPE html>
<html>
<head>
  <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" />
  <meta charset="utf-8">
  <title>Chartist | Simple line chart</title>
</head>
<body>
  <div class="ct-chart"></div>
</body>
</html>

Now we can initialize a line chart on the container with only a few lines of JavaScript. Let’s create three series, with five values each. We’ll also set a list of labels for the x-axis. As a second argument, the Chartist.Line constructor accepts an options object. Here, we can specify a fixed width and height for our 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 Link

In the example above, we used a fixed width and height for the chart. This is not always desired, and in responsive design we should keep our elements fluid and not think in fixed dimensions.

Chartist uses its own classes to set containers with fixed aspect ratios (intrinsic ratios). Usually, this is a technique applied to responsive videos and iframes, and it uses the intrinsic ratio CSS trick7 to establish a fixed ratio container. With the implementation in Chartist8, you can even set the width of a container while preserving the aspect ratio.

Let’s use one of the generated responsive container classes in Chartist to size our chart. I’ve picked ct-golden-section, but you can choose any from the list of generated container classes9. When using the Sass version of Chartist, you can also generate your own fixed-aspect-ratio containers easily.

<body>
  <div class="ct-chart ct-golden-section"></div>
</body>

Because we are now specifying a container with a fixed aspect ratio on our chart, we no longer need to rely on fixed dimensions when initializing our chart. Let’s remove the width and height in our 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 chart that responds to changes in media. Try resizing the output panel on JSBin to see how the chart adapts to changes in window size.

Advanced Configuration Link

One of Chartist’s core principles is a clean separation of concerns via standard web technologies. This includes applying all appearance-related settings with CSS. Also, a number of settings allow you to control the behavior of your chart. These settings are applied using JavaScript and can be passed to your chart during initialization.

Let’s create a simple bar chart that visualizes some data for weekdays.

A simple bar chart with two series11

A simple bar chart with two series
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 the options, we can control the distance of the bars and tell Chartist not to render the grid on the x-axis. For a complete list of options, you can always visit Chartist’s API documentation13.

By default, the labels on the x-axis are left-aligned. To make them center-aligned, we need to add a CSS style. We also want to change the bar’s width 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 chart for large screens.

Responsive Configuration Override Link

The example above works nicely on desktop screens, but not on devices with tight screen resolutions. The bars are too wide, the labels too large and the names of the weekdays are written in full. Also, the distance of the bars needs to be adjusted.

Some of these changes can be done in CSS by modifying the bar’s width in a media query. But how do we go about applying different configurations in JavaScript? Chartist provides a mechanism for this purpose called responsive configuration override.

Let’s look at the previous example and rewrite it with a mobile-first approach. We’ll optimize our media queries for the content we’re working with, introducing a breakpoint at 300 pixels and another at 600 pixels.

.ct-chart .ct-label.ct-horizontal {
  text-align: center;
}
.ct-chart .ct-bar {
  stroke-width: 5px;
}
@media screen and (min-width: 300px) {
  .ct-chart .ct-bar {
    stroke-width: 10px;
  }
}
@media screen and (min-width: 600px) {
  .ct-chart .ct-bar {
    stroke-width: 20px;
  }
}

If we’d like to tailor our chart to a particular medium, we can use the responsive configuration overrides. We simply tell Chartist to inherit and override our configuration based on the same media queries in our CSS. Chartist uses window.matchMedia15 to implement an inheritance in our settings similar to what CSS does with our styles.

Bar chart with responsive configuration overrides16

Bar chart with responsive configuration overrides

The following example uses labelInterpolationFnc to pass a function that enables us to interpolate or even replace the label’s original value for the given axis. This means we can control how the weekdays’ names are displayed on the 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 return first letter of weekday names
    labelInterpolationFnc: function(value) {
      return value[0];
    }
  }
}, [
  // Over 300px, we change the bar distance and show the first three letters of the weekdays
  ['screen and (min-width: 300px)', {
    seriesBarDistance: 15,
    axisX: {
      labelInterpolationFnc: function(value) {
        return value.slice(0, 3);
      }
    }
  }],
  // Over 600px, we increase the bar distance one more time and show the full weekdays
  ['screen and (min-width: 600px)', {
    seriesBarDistance: 30,
    axisX: {
      labelInterpolationFnc: function(value) { return value; }
    }
  }]
]);

Edit on JSBin17

In the example above, you can see how easy it is to create a chart that works on both mobile and desktop, while maintaining a clean separation of concerns.

Styling SVG With CSS Link

Styling inline SVG with CSS is easy and efficient because you’re able to reuse styles for different charts. You can include CSS classes that define the look and feel of your charts and that keep the logic separated from the appearance.

Here are some of the most useful CSS properties for styling inline SVG:

  • fill
    Sets the color of a shape’s fill. You may use RGBa.
  • stroke
    Sets the color of the outline around your shape.
  • stroke-width
    Sets the width of an outline.
  • stroke-dasharray
    Specifies a dashed stroke for an outline.
  • stroke-linecap
    Sets the line-cap stroke for the outline of a shape. This can be set to round, butt or square.

Check the SVG 1.1 specification for a complete list of SVG styling properties18.

A chart with custom CSS styling19

A chart with custom CSS styling

Let’s apply our new styling skills and create a line chart with three different looking series. We’ll use all of the above styling properties to give our chart a unique 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: #4ECDC4;
  stroke-width: 10px;
  stroke-linecap: round;
}
.ct-chart .ct-series.ct-series-b .ct-line {
  stroke: #C7F464;
  stroke-width: 2px;
  stroke-dasharray: 5px 2px;
}
.ct-chart .ct-series.ct-series-c .ct-line {
  stroke: #FF6B6B;
  stroke-width: 3px;
  stroke-linecap: round;
  stroke-dasharray: 30px 5px;
}

Edit on JSBin20

If you play around with this example a bit, you’ll quickly see how easy it is to style SVG with CSS. Also, you might have noticed the shape-rendering: crispEdges style on the grid lines. While I haven’t included the shape-rendering property in the list of useful styling properties, you’ll find it quite handy in some situations. It allows you to give the browser some hints on how to render SVG. The values auto, optimizeSpeed, crispEdges and geometricPrecision are supported by the specification. Intended for performance control, this property is also handy for rendering certain shapes without anti-aliasing. In some charts, including the example above, making the grid lines look very crisp with the crispEdges value has a very nice effect.

CSS Animation Craziness Link

I’m a huge fan of animation… well, as long as it supports the content and conveys information to the user. It can mean the difference between a UX playing nicely and not. Google’s material design21 is a great example of functional animation design. However, for this article, we will not focus on functional animation, but instead go a bit crazy with the possibilities at our disposal. Browser support for animation of SVG properties is pretty stable now, and you can even animate the stroke-dasharray and stroke-dashoffset properties. Let’s enhance the previous example with some meaningful animation.

Animated chart using CSS animation22

Animated chart using CSS animation

Simply by using some CSS3, we are able to create some crazy animations in our 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: #4ECDC4;
  stroke-width: 10px;
  stroke-linecap: round;
  animation: width-pulse 2s infinite;
}
.ct-chart .ct-series.ct-series-b .ct-line {
  stroke: #C7F464;
  stroke-width: 2px;
  stroke-dasharray: 5px 2px;
  animation: dashoffset-seven 200ms infinite linear;
}
.ct-chart .ct-series.ct-series-c .ct-line {
  stroke: #FF6B6B;
  stroke-width: 3px;
  stroke-linecap: round;
  stroke-dasharray: 30px 5px;
  animation: dasharray-craziness 10s infinite linear;
}

Edit on JSBin23

As you can see, styling and animating SVG using CSS is a lot of fun. If you’d like more information, I recommend the article by Sara Soueidan “Styling and Animating SVGs With CSS24.”

Animating With SMIL Link

CSS animation is a great way to inject some life into a chart. There are some things you can’t animate with CSS, though. If you want to animate individual parameters of an SVG element to morph a shape, then you would use the Chartist.Svg APIs to conveniently create SMIL animations.

SMIL is powerful, but the declarative API, which uses <animate> elements, can be confusing in its complexity. Chartist offers a high-level API that enables you to easily take advantage of SMIL animations in your charts.

The goal of Chartist is to simplify the handling of SMIL while preserving the semantics specified by the W3C. Chartist uses its own SVG manipulation library, which is accessible through Chartist.Svg. Similar to jQuery, it provides a wrapper object around real SVG DOM nodes, giving you some convenient methods to manipulate the underlying SVG. You can get a complete overview by browsing the Chartist.Svg API documentation25.

To animate an SVG element, you first need to obtain a wrapper object by passing an SVG node to the Chartist.Svg constructor.

var element = new Chartist.Svg(document.querySelector('#my-specific-svg-element'));

You can then call the animate function on your wrapped element with an animation definition 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 create three SMIL <animate> elements, each of which contains the SMIL animation attributes specified in the definition objects. The Chartist animation API has a few particularities. The begin and dur (i.e. duration) properties may be specified as unitless numbers; Chartist will convert the numbers to milliseconds automatically. Chartist also supports an easing property in the animation definition object that is not directly supported by SMIL. The easing property allows you to specify an easing function from Chartist.Svg.Easing, which will be translated to a SMIL interpolation function.

Chartist handles SMIL animations in a special guided mode by default. The guided mode includes the following behavior, which makes handling and optimization easier for immediately triggered animations:

  • Before the animation starts (even when delayed with begin), the animated attribute will already be set to the from value of the animation.
  • begin is explicitly set to indefinite so that it can be started manually without relying on the document’s begin time (i.e. creation).
  • The animate element is forced to use fill="freeze".
  • The animation is triggered with beginElement() in a timeout, where the beginning of the definition object is interpreted in milliseconds. If no beginning is specified, then the timeout is triggered immediately.
  • After the animation, the element’s attribute value is set to the to value of the animation.
  • The animate element is then deleted from the DOM.

You can also disable guided mode by passing false as the second argument to the animate function.

Animating Chart Elements Using the Event API Link

Chartist provides a few events that you can use to intercept the creation process of charts. The draw events of Chartist get triggered each time a chart element is created in the DOM. Since we have the Chartist.Svg wrapper and all relevant data available in the event callback, this makes it a perfect spot to add our animations.

Chart with SMIL animations26

Chart with SMIL animations

This example looks more like a confetti party than a chart, but it should illustrate how easy it is to create custom animations. The example makes use of the Chartist event 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 Link

Because Chartist uses inline SVG in the DOM, extending the core functionality is very easy. While SVG elements in the DOM have the same events as regular DOM elements, you can easily use the DOM library of your choice and add custom functionality to your chart’s elements.

Chart with custom tooltip28

Chart with custom tooltip

This example shows you how to add a simple tooltip to a chart using jQuery. When the user hovers over a data point, the tooltip should become visible and display the data 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 example above uses regular DOM events to add a simple tooltip. You might have noticed the use of the ct:value attribute from the line chart’s point element and the ct:series-name attribute from the series group. Chartist has its own XML namespace, which it uses to expose some meta data to the SVG. This makes it easy to extract information from the DOM and use it for custom functionality.

Extending the Drawing Pipeline Link

The event system of Chartist is powerful and is a great tool to extend your chart with custom features. The following example uses the draw event of the line chart to replace the boring point elements with something smashing.

Chart with Smashing Magazine logo using Chartist draw event

Chart with Smashing Magazine’s logo using Chartist’s draw event
var smashingImgTag = '<img src="https://www.smashingmagazine.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);
  }
});

In the example above, we’ve replaced each point element just after it has been drawn (inserted in the DOM tree) with a foreignObject that contains an image. A foreignObject allows you to embed HTML elements in an SVG. The Chartist.Svg API provides an easy and convenient way to create foreignObjects. For details on the Chartist.Svg API, visit the API documentation30.

Resources Link

Contribute Link

We are constantly looking for people to get involved. If you have some spare time and are interested in contributing, please grab an issue to work on or open a new one.

(vf, al, il)

Footnotes Link

  1. 1 http://gionkunz.github.io/chartist-js/
  2. 2 https://github.com/umdjs/umd
  3. 3 https://hacks.mozilla.org/2014/11/jsdelivr-and-its-open-source-load-balancing-algorithm/
  4. 4 http://jsbin.com/
  5. 5 http://jsbin.com/qalewi
  6. 6 http://jsbin.com/qalewi/edit?js,output
  7. 7 http://alistapart.com/article/creating-intrinsic-ratios-for-video
  8. 8 https://github.com/gionkunz/chartist-js/blob/develop/src/styles/chartist.scss#L4-L30
  9. 9 http://gionkunz.github.io/chartist-js/getting-started.html#creating-a-chart-using-aspect-ratios
  10. 10 http://jsbin.com/quyamo/edit?js,output
  11. 11 http://jsbin.com/kebaye
  12. 12 http://jsbin.com/kebaye/edit?js,output
  13. 13 http://gionkunz.github.io/chartist-js/api-documentation.html
  14. 14 http://jsbin.com/kebaye/edit?css,output
  15. 15 https://developer.mozilla.org/en-US/docs/Web/API/Window.matchMedia
  16. 16 http://jsbin.com/ciyunu
  17. 17 http://jsbin.com/ciyunu/edit?js,css,output
  18. 18 http://www.w3.org/TR/SVG/styling.html#SVGStylingProperties
  19. 19 http://jsbin.com/zoruko
  20. 20 http://jsbin.com/zoruko/edit?css,output
  21. 21 http://www.google.com/design/spec/animation/meaningful-transitions.html
  22. 22 http://jsbin.com/jovuh
  23. 23 http://jsbin.com/jovuh/edit?css,output
  24. 24 https://www.smashingmagazine.com/2014/11/03/styling-and-animating-svgs-with-css/
  25. 25 http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-function-svg
  26. 26 http://jsbin.com/zumubi
  27. 27 http://jsbin.com/zumubi/edit?js,output
  28. 28 http://jsbin.com/seruk
  29. 29 http://jsbin.com/seruk/edit?js,output
  30. 30 http://gionkunz.github.io/chartist-js/api-documentation.html#chartistsvg-constructor-svg
  31. 31 http://gionkunz.github.io/chartist-js/api-documentation.html
  32. 32 http://gionkunz.github.io/chartist-js/examples.html
  33. 33 http://www.w3.org/TR/SVG/
  34. 34 http://www.w3.org/TR/SMIL3/smil-animation.html
  35. 35 https://developer.mozilla.org/en-US/docs/Web/SVG/Element/foreignObject
SmashingConf New York

Hold on, Tiger! Thank you for reading the article. Did you know that we also publish printed books and run friendly conferences – crafted for pros like you? Like SmashingConf Barcelona, on October 25–26, with smart design patterns and front-end techniques.

↑ Back to top Tweet itShare on Facebook

Gion is a front-end developer and consultant with a strong love to beautiful design. His work includes responsive web design, web application development and development process optimizations. As a consultant he supports large organizations to keep up with the latest front end trends and coaches them on how to adopt the best parts of the modern web in their individual context. He's also a frequent speaker, workshop leader and co-organizer of the Angular.js Meetup Zurich.

Gion's CodePen Profile

Gion's Public Presentations

  1. 1

    Excellent article, I guess I’ll have to add more features to https://github.com/soderlind/tablepress_chartist

    0
  2. 2

    Christopher Erk

    December 16, 2014 8:36 pm

    This is great! Thanks for adding the part about the tooltip(s). :)

    0
  3. 3

    طراحی سایت

    December 16, 2014 9:44 pm

    Thanks for post!!!

    0
  4. 4

    Nice one. I have used some graphing libraries in the past, and they always seem to spiral out of control pretty quickly, so there is definitely a need for a simple and responsive library to compete with these.

    0
  5. 5

    This is interesting. My only thoughts are, how is this different to chart.js? Chart.js handles responsivity very well, as stated on their website (http://www.chartjs.org/).

    I totally agree that responsive is a must have these days, but from my experience using chart.js there’s nothing I’m really lacking. Intrigued to hear why people would prefer chartist.js

    0
    • 6

      Hi Fred. Thanks for reading the article. I love Chart.js because it was one of the first charting libraries that was sticking to a simple design and provide very simple and basic charts. This is also one of the main claims of Chartist. I think it’s a general misbelief today that by providing re-sizable content your content is responsive. Responsible responsive content means that you’re considering the full context in which your content appears and provide the ideal solution to convey the information. This simply can’t be done by only re-size your content. Chartist provides much more than flexible containers. It provides different label text, shapes, colors, animations, space all depending on the context using CSS3 media queries and the responsive configuration override mechanism.

      Here are some bullet points if you’re more the spec comparison guy:
      – Chartist uses SVG over canvas which brings a whole bunch of benefits that can be summarized in the following main points
      – Use CSS to style your chart elements and also use media queries to style your chart for different media
      – You can use CSS3 animations on your chart elements
      – Attach DOM event listeners (click, mouseenter etc.) to your chart elements to add custom interactions easily. Try implement this on canvas!
      – You’re fully DPI independent with SVG while for canvas you’d need to do the 50% width hack and use double the size for your canvas. This also only works for DPI x 2, how do you go about x3, x2.46, x1.6667 ? Of course you could use window.devicePixelRatio but do you really want to go down this road?
      – You can use SMIL animations which are really awesome!
      – Chartist provides something called responsive configuration override, which lets you customize your content for different media with a very fine granularity
      – With the plugin mechanism of Chartist your possibilities for extending the library are nearly infinite
      – By leveraging inline SVG in the DOM and a proper separation of concerns using CSS your charts will fit your design almost automatically
      – Chart.js and Chartist are both quite light weights where Chartist (at the time of writing) with ~20KB

      1
      • 7

        Hi Gion, thanks very much for taking the time to respond.

        Chart.js definitely has some level of understanding the context, with it showing more details at larger sizes and less at smaller.

        The point about it being SVG is a pretty big one though, that’s quite interesting. I appreciate the article, I’ll take a closer look.

        -1
      • 8

        “Attach DOM event listeners (click, mouseenter etc.) to your chart elements to add custom interactions easily. Try implement this on canvas!”

        It’s fairly easy to implement. You know when and where on the canvas (eg.element area) the cursor is clicked, and implement callbacks.

        Otherwise, agreed. CSS3 styling, animation being the biggest advantage

        0
  6. 9

    Wow! This is great. This will be a great help! (y)

    -2
  7. 10

    Looks interesting and might be good if you need something simple like that. But for more complex results (or if you need to support legacy browsers like IE8) you will need to go for highcharts (http://www.highcharts.com) or amCharts (www.amcharts.com) that are obvious market leaders and trend setters.

    0
    • 11

      Hey Tom. Thanks for your comment. I think Highcharts and amCharts are great libraries but as you already said they have a different claim. They are more enterprise graphing libraries and are both subject to a charge if used commercially. They both come with a payload of about 200KB where Chartist is a lightweight library (~20KB) that provides you with all you need to create simple responsive charts. It’s also about a different philosophy that starts with the fact that you can’t control appearance relevant configuration through JavaScript in Chartist but use CSS to style your chart. Most libraries use JavaScript to control color and shape which first looks nice but quickly turns into a mess as you loose the clean separation of concerns HTML, CSS and JavaScript provides. If you need to support legacy browsers or need to plot complicated charts (like financial or very technical charts) I’d definitely recommend Highcharts, amCharts or any other great charting library.

      0
    • 12

      ZingChart (http://www.zingchart.com/) and plotly (https://plot.ly/javascript-graphing-library/) are some other great options as well.

      0
  8. 13

    Definitely, this is good article to create a chart according to our choice and need. I hope you will post this type of knowledgeable article in the future.

    0
  9. 14

    thanks for this article, it was great!

    0
  10. 15

    Any way to remove the last section in graph? (take a look at any line graph, last one for example).
    It looks so messy.

    0
    • 16

      Hi Armands. If your graph consists of only a few data points it indeed looks strange to have the additional “empty” segment on the line chart. This is due to the label arrangement on the chart and becomes less a problem if the number of data points increase. If you’d like to skip the last segment and use the full width of the chart you can add the option fullWidth: true to your line or bar chart configuration. However, you’ll need to rearrange your labels so that the last one doesn’t get cut off. This needs to tweaking but can be done in a clean way. You can visit this jsbin to see an example: http://jsbin.com/wudom/1/edit?css,js,output

      0
  11. 17

    You should join in a contest initial of the greatest blogs on the web. I will recommend this web internet site!

    0
  12. 18

    Henrik Östman

    December 22, 2014 7:45 am

    Hi Gion!

    And thanks for your nice graph-library, the API looks really clean and the graphs scales very well.
    Could you please provide me a short comparison of chartist and D3 (https://github.com/mbostock/d3)?
    D3 has been around for a long while, have plenty of examples and documentation, and as I understand it is based upon HTML and SVG also. I have not tested its responsiveness, maybe that’s chartist main selling point? Chartist have a nicer API though. Could you and other reades here provide me with some more info, please?

    0
    • 19

      Hi Henrik

      Sorry for the late reply on your question. I was distracted with vacation ;-)

      It’s very difficult to compare Chartist with D3. Maybe a good analogy would be to say that D3 is a swiss army knife with 30 different tools all embedded into one big, bulky and heavy “knife” and Chartist is a regular pocket knife with a short, medium and large blade. Same as with the swiss army knife in D3 you’re not limited to craft anything specific. D3 allows you to build any kind of data visualization based on a huge amount of helper functions and a very powerful transformation language to transform data into graphics. However, D3 is rather bulky (~150KB) and you can’t go without a manual at your hands when you’re planing to use it. Also the learning curve is quite steep as you first need to understand their (brilliant) data transformation / selection concept. On the other hand, Chartist or the simple 3 blade knife fits into your pocket very easily, you know exactly how to use it and it does one thing just right. For Chartist that’s building Simple Responsive Charts and with its weight of ~20KB it’s optimized to exactly this simple but demanding job. One major goal was also to keep the configuration as simple as possible but at the same time to provide extensibility so that you’re not limited to a certain way of using it.

      If you know that for a rather large project you’ll need to create custom data visualizations that vary a lot I’d recommend you to look at D3 as it allows you to craft any data visualization you can imagine. A perfect example is an online representation of a newspaper. They need to visualize elections, statistics on various geographically bound data and other complex and very custom visualizations.

      In cases where you need simple charts that support you in building them responsive responsibly, then Chartist might be the tool for you.

      I hope this gives you a better overview.

      Cheers
      Gion

      2
  13. 21

    It’s pity ! No radar charts ! !

    2
  14. 22

    This is great!

    0
  15. 23

    Hi Gion, this all looks great but I do have one question.

    Can you create a legend/key within chartist.js to show what the different lines or bars actually refer to?

    For example, if the animated dashed green line above was sales of apples over the months of the year how would you know that without adding a tooltip?

    6
  16. 24

    That is very cool, i’ve been looking for some charts that work responsively, I know Google Charts do an ok job, but this looks a lot slicker.

    0
  17. 25

    It’s amazing but hard to learn…

    0
  18. 26

    Great, it’s just what I need!

    0
  19. 27

    Try LiveGap Charts ( http://charts.livegap.com) . Free Online Tool to Create animated charts (More than 9 types Of Charts). Build on ChartNew.js library
    Customize Colors,GradientsText,fonts,Margin….. save it as static image or as HTMl To Use Online.

    1
  20. 28

    Jameela Khasef Almawali

    April 26, 2015 8:13 am

    I want code for function drawingLibarary.js draw home

    0

↑ Back to top