Chartist - Getting started

Download and set-up

Bower

The easiest way to get started with Chartist.js is by using bower:

bower install chartist --save

The bower package contains the JavaScript library, CSS as well as the Sass (SCSS) files. You can then integrate the desired dependencies in your project and start using them immediately.

One, two, three, CSS!

The quickest way to get things up and running is by using the Chartist.js CSS files. The CSS is compiled from the Sass files with the default class names which are also configured in the JavaScript library. You can then override the default styles or modify the CSS file, however, for customization it's recommended to use the Sass version of Chartist.js.

<!DOCTYPE html>
<html>
  <head>
    <title>My first Chartist Tests</title>
    <link rel="stylesheet"
          href="bower_components/chartist/dist/chartist.min.css">
  </head>
  <body>
    <!-- Site content goes here !-->
    <script src="bower_components/chartist/dist/chartist.min.js"></script>
  </body>
</html>
Use a CDN alternatively

If you'd like to get started even faster you can also use a CDN to load Chartist.js. The awesome people at jsDelivr provide a fantastic job in hosting libraries from over 42 POP Locations around the world! They always update Chartist.js to the latest version immediately and they do all that for free! Check out the jsDeliver website for more information.

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css">
    <script src="//cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
  </head>
</html>

The Sass way

If you like to customize your charts you can either remove the CSS fully and write your own selectors using the Chartist.js Sass mixins or you just use the Chartist.js Sass settings file to customize the look and feel of your charts.

Styling inline SVG with CSS is a breeze and you should also consider writing your own selectors for your charts and using the Sass mixins. You can read more about using the Sass mixins in the advanced section.

To customize the style of your charts using the Sass settings file you should copy the settings file to your own Sass folder.

cp bower_components/chartist/dist/scss/settings/_chartist-settings.scss styles

Then just import your copy of the settings file before you import the chartist.scss file and change the settings in your copy as desired.

@import "_my-chartist-settings.scss";
@import "chartist/dist/scss/chartist.scss";
Default settings

The settings file contains all relevant variables used in the mixins and while generating the default classes. You can simply change the settings for styling your own charts. If you want to override certain settings based on state or pseeudo selectors, you can use the individual mixins to only override specific styles.

Take a look at the settings to see how to customize the style of the defalt Chartist.js class selectors.

// Scales for responsive SVG containers
$ct-scales: ((1), (15/16), (8/9), (5/6), (4/5), (3/4), (2/3), (5/8), (1/1.618), (3/5), (9/16), (8/15), (1/2), (2/5), (3/8), (1/3), (1/4)) !default;
$ct-scales-names: (ct-square, ct-minor-second, ct-major-second, ct-minor-third, ct-major-third, ct-perfect-fourth, ct-perfect-fifth, ct-minor-sixth, ct-golden-section, ct-major-sixth, ct-minor-seventh, ct-major-seventh, ct-octave, ct-major-tenth, ct-major-eleventh, ct-major-twelfth, ct-double-octave) !default;

// Class names to be used when generating CSS
$ct-class-chart: ct-chart !default;
$ct-class-chart-line: ct-chart-line !default;
$ct-class-chart-bar: ct-chart-bar !default;
$ct-class-horizontal-bars: ct-horizontal-bars !default;
$ct-class-chart-pie: ct-chart-pie !default;
$ct-class-chart-donut: ct-chart-donut !default;
$ct-class-label: ct-label !default;
$ct-class-series: ct-series !default;
$ct-class-line: ct-line !default;
$ct-class-point: ct-point !default;
$ct-class-area: ct-area !default;
$ct-class-bar: ct-bar !default;
$ct-class-slice-pie: ct-slice-pie !default;
$ct-class-slice-donut: ct-slice-donut !default;
$ct-class-slice-donut-solid: ct-slice-donut-solid !default;
$ct-class-grid: ct-grid !default;
$ct-class-grid-background: ct-grid-background !default;
$ct-class-vertical: ct-vertical !default;
$ct-class-horizontal: ct-horizontal !default;
$ct-class-start: ct-start !default;
$ct-class-end: ct-end !default;

// Container ratio
$ct-container-ratio: (1/1.618) !default;

// Text styles for labels
$ct-text-color: rgba(0, 0, 0, 0.4) !default;
$ct-text-size: 0.75rem !default;
$ct-text-align: flex-start !default;
$ct-text-justify: flex-start !default;
$ct-text-line-height: 1;

// Grid styles
$ct-grid-color: rgba(0, 0, 0, 0.2) !default;
$ct-grid-dasharray: 2px !default;
$ct-grid-width: 1px !default;
$ct-grid-background-fill: none !default;

// Line chart properties
$ct-line-width: 4px !default;
$ct-line-dasharray: false !default;
$ct-point-size: 10px !default;
// Line chart point, can be either round or square
$ct-point-shape: round !default;
// Area fill transparency between 0 and 1
$ct-area-opacity: 0.1 !default;

// Bar chart bar width
$ct-bar-width: 10px !default;

// Donut width (If donut width is to big it can cause issues where the shape gets distorted)
$ct-donut-width: 60px !default;

// If set to true it will include the default classes and generate CSS output. If you're planning to use the mixins you
// should set this property to false
$ct-include-classes: true !default;

// If this is set to true the CSS will contain colored series. You can extend or change the color with the
// properties below
$ct-include-colored-series: $ct-include-classes !default;

// If set to true this will include all responsive container variations using the scales defined at the top of the script
$ct-include-alternative-responsive-containers: $ct-include-classes !default;

// Series names and colors. This can be extended or customized as desired. Just add more series and colors.
$ct-series-names: (a, b, c, d, e, f, g, h, i, j, k, l, m, n, o) !default;
$ct-series-colors: (
  #d70206,
  #f05b4f,
  #f4c63d,
  #d17905,
  #453d3f,
  #59922b,
  #0544d3,
  #6b0392,
  #f05b4f,
  #dda458,
  #eacf7d,
  #86797d,
  #b2c326,
  #6188e2,
  #a748ca
) !default;

Create your first chart

In this section you'll go through a simple example of how to use Chartist.js in your project. You'll learn the default stages you go through when creating and customizing a basic line chart. If you'd like to see more in depth and advanced examples you should check out the advanced section or the examples page.

As simple as it can get

Chartist provides you a very simple API to get started, however, while trying to follow the best practice of relying on standards and clear separation of concerns it sometimes needs a small mind shift in order to understand how things are meant to work within Chartist. Instead of specifying your colors, line width and other style related things in the JavaScript API, you'll need to use CSS in order to control your appearance.

Creating a chart using aspect ratios

Because of the nature of responsive design it's important to understand that blocks in design like images, videos and similar content need to be able to scale and adapt to the media. In order for an element to scale, you need to rely on a certain aspect ratios (like 4:3, 3:2, 16:9 etc.) rather than specifying a fixed width and height.

To designers this Idea is absolutely not new, but to developers this might be at first. However, when a designer talks to a developer about the images being 320x240 on this page and 300x200 on that element, he actually just translated his idea of using 4:3 and 3:2 images into pixels.

With Chartist you can specify those ratios directly on containers without the need to calculate any fixed dimensions. In order to create a chart that is using the aspect ratio of a golden section you can just add the class .ct-golden-section to your container where you initialize Chartist.

Here is a list of all available container ratios (If using the Sass version of Chartist you can also easily add others):

Show available aspect ratios

Use the following HTML code to specify a container with one of the above aspect ratio classes.

<div class="ct-chart ct-perfect-fourth"></div>

When using a fixed aspect ratio container you can then simply initialize your chart without specifying any width or height in the options.

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]
  ]
};

// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object.
new Chartist.Line('.ct-chart', data);
Creating a chart with fixed dimensions

In order to create a simple line chart with fixed width and height you only need to have a container element and initialize Chartist.js on it. Give the container the class ct-chart so that it will get the default styles (if you don't use your own classes).

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. We can also omit this and use aspect ratio containers
// as you saw in the previous example
var options = {
  width: 300,
  height: 200
};

// Create a new line chart object where as first parameter we pass in a selector
// that is resolving to our chart container element. The Second parameter
// is the actual data object. As a third parameter we pass in our custom options.
new Chartist.Line('.ct-chart', data, options);
More than one chart on my page?

The example above uses the chartist default class to select the element where the chart should be created. This class is important for applying the right styles in the CSS of Chartist. If you need to create individual charts on one page, you should use IDs to initialize them separately.

<div class="ct-chart ct-golden-section" id="chart1"></div>
<div class="ct-chart ct-golden-section" id="chart2"></div>

<script>
  // Initialize a Line chart in the container with the ID chart1
  new Chartist.Line('#chart1', {
    labels: [1, 2, 3, 4],
    series: [[100, 120, 180, 200]]
  });

  // Initialize a Line chart in the container with the ID chart2
  new Chartist.Bar('#chart2', {
    labels: [1, 2, 3, 4],
    series: [[5, 2, 8, 3]]
  });
</script>

The configuration of your chart

Chartist.js is built very flexible and almost everything within your charts can be configured. In the default settings (that you can check in the API Documentation) you'll get some predefined defaults applied to your charts.

You can always override the default settings of your charts by passing in a configuration object at creation time.

// Our labels and three data series
var data = {
  labels: ['Week1', 'Week2', 'Week3', 'Week4', 'Week5', 'Week6'],
  series: [
    [5, 4, 3, 7, 5, 10],
    [3, 2, 9, 5, 4, 6],
    [2, 1, -3, -4, -2, 0]
  ]
};

// We are setting a few options for our chart and override the defaults
var options = {
  // Don't draw the line chart points
  showPoint: false,
  // Disable line smoothing
  lineSmooth: false,
  // X-Axis specific configuration
  axisX: {
    // We can disable the grid for this axis
    showGrid: false,
    // and also don't show the label
    showLabel: false
  },
  // Y-Axis specific configuration
  axisY: {
    // Lets offset the chart a bit from the labels
    offset: 60,
    // The label interpolation function enables you to modify the values
    // used for the labels on each axis. Here we are converting the
    // values into million pound.
    labelInterpolationFnc: function(value) {
      return '$' + value + 'm';
    }
  }
};

// All you need to do is pass your configuration as third parameter to the chart function
new Chartist.Line('.ct-chart', data, options);

Responsive sugar topping

Responsive web design is all based on media queries as you are probably already aware. Media queries are great and they help you to define media related conditions that you can use to apply different styles for different media.

Sometimes it's also required to have different behavior on certain media and it's possible that a specific component of your web site should behave in an other way on a small media than on a large one. Luckily there is window.matchMedia in your browser that comes to the rescue. With matchMedia it's possible to let your javascript react differently based on CSS3 media queries.

Responsive setting overrides

Configuring different chart behavior for various media is made simple with an override mechanism. The priority of the override mechanism is based on order of specification of the matching media queries.

The following example uses different label interpolations (to save some space) on small media as well as different spacing between the bars of the bar chart series. Resize your browser window to see the effect.

var data = {
  labels: ['Jan', 'Feb', 'Mar', 'Apr', 'Mai', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
    series: [
    [5, 4, 3, 7, 5, 10, 3, 4, 8, 10, 6, 8],
    [3, 2, 9, 5, 4, 6, 4, 6, 7, 8, 7, 4]
  ]
};

var options = {
  seriesBarDistance: 15
};

var responsiveOptions = [
  ['screen and (min-width: 641px) and (max-width: 1024px)', {
    seriesBarDistance: 10,
    axisX: {
      labelInterpolationFnc: function (value) {
        return value;
      }
    }
  }],
  ['screen and (max-width: 640px)', {
    seriesBarDistance: 5,
    axisX: {
      labelInterpolationFnc: function (value) {
        return value[0];
      }
    }
  }]
];

new Chartist.Bar('.ct-chart', data, options, responsiveOptions);
Cross-browser support
For IE9 you need to use a matchMedia polyfill. You should take a look at Paul Irish's matchMedia polyfill. Make sure you include matchMedia.js as well as matchMedia.addListener.js as always both are needed to polyfill the full specification of window.matchMedia.

Different configuration for different series

Chartist also allows you to add specific configuration overrides for your series. This is useful if you want to combine different looks for your series on the same chart.

You can even take this one step further by again overriding your series configuration in some responsive settings overrides. This sounds complicated but it actually is very simple. Check the example code with inline comments below to see how easy it is.

var chart = new Chartist.Line('.ct-chart', {
  labels: ['1', '2', '3', '4', '5', '6', '7', '8'],
  // Naming the series with the series object array notation
  series: [{
    name: 'series-1',
    data: [5, 2, -4, 2, 0, -2, 5, -3]
  }, {
    name: 'series-2',
    data: [4, 3, 5, 3, 1, 3, 6, 4]
  }, {
    name: 'series-3',
    data: [2, 4, 3, 1, 4, 5, 3, 2]
  }]
}, {
  fullWidth: true,
  // Within the series options you can use the series names
  // to specify configuration that will only be used for the
  // specific series.
  series: {
    'series-1': {
      lineSmooth: Chartist.Interpolation.step()
    },
    'series-2': {
      lineSmooth: Chartist.Interpolation.simple(),
      showArea: true
    },
    'series-3': {
      showPoint: false
    }
  }
}, [
  // You can even use responsive configuration overrides to
  // customize your series configuration even further!
  ['screen and (max-width: 320px)', {
    series: {
      'series-1': {
        lineSmooth: Chartist.Interpolation.none()
      },
      'series-2': {
        lineSmooth: Chartist.Interpolation.none(),
        showArea: false
      },
      'series-3': {
        lineSmooth: Chartist.Interpolation.none(),
        showPoint: true
      }
    }
  }]
]);

Styling your chart

You should always use the power of CSS to make your data pop into your visitors eyes. I know I’m telling this over and over but it’s all about a clean separation of concerns. In this chapter you’ll find some useful information on how to style your charts with CSS.

Customizing the default CSS

Chartist comes with a highly customizable Sass file that allows you to customize all sorts of appearance relevant things on your charts including colours used for series, line styles, thickness and other properties. If you have the advantage of having a Sass build process at your disposal, I highly recommend you to use the Sass version of Chartist instead of the already prebuilt CSS. For more information on how to use the Sass version please check out the Sass way of Chartist.

Chartist generates predefined classes for series by default. Those class names are alphabetically ordered and always start with ct-series-a, where the letter a will be iterated with each series count (a, b, c, d etc.). To address a specific series in styling, you’ll need to create some styles for the corresponding series class name.

Here is a list of selectors from the different chart types with some comments to explain what properties can be used to influence the visual style of your charts.

Line chart
/* Use this selector to override the line style on a given series */
.ct-series-a .ct-line {
  /* Set the colour of this series line */
  stroke: red;
  /* Control the thikness of your lines */
  stroke-width: 5px;
  /* Create a dashed line with a pattern */
  stroke-dasharray: 10px 20px;
}

/* This selector overrides the points style on line charts. Points on line charts are actually just very short strokes. This allows you to customize even the point size in CSS */
.ct-series-a .ct-point {
  /* Colour of your points */
  stroke: red;
  /* Size of your points */
  stroke-width: 20px;
  /* Make your points appear as squares */
  stroke-linecap: square;
}
Bar chart
/* Use this selector to override bar styles on bar charts. Bars are also strokes so you have maximum freedom in styling them. */
.ct-series-a .ct-bar {
  /* Colour of your bars */
  stroke: red;
  /* The width of your bars */
  stroke-width: 20px;
  /* Yes! Dashed bars! */
  stroke-dasharray: 20px;
  /* Maybe you like round corners on your bars? */
  stroke-linecap: round;
}
Pie chart
/* Pie charts consist of solid slices where you can use this selector to override the default style. */
.ct-series-a .ct-slice-pie {
  /* fill of the pie slieces */
  fill: hsl(120, 40%, 60%);
  /* give your pie slices some outline or separate them visually by using the background color here */
  stroke: white;
  /* outline width */
  stroke-width: 4px;
}
Donut chart
/* Donut charts get built from Pie charts but with a fundamentally difference in the drawing approach. The donut is drawn using arc strokes for maximum freedom in styling */
.ct-series-a .ct-slice-donut {
  /* give the donut slice a custom colour */
  stroke: blue;
  /* customize stroke width of the donut slices in CSS. Note that this property is already set in JavaScript and label positioning also relies on this. In the right situation though it can be very useful to style this property. You need to use !important to override the style attribute */
  stroke-width: 5px !important;
  /* create modern looking rounded donut charts */
  stroke-linecap: round;
}

Colour up your charts

Colour is a core attribute of appearance and as you already know, we believe in strong separation of concerns in web development. Therefore, Chartist does not include any options within the JavaScript API to control colour of your charts.

This might first seem very inconvenient, but you’ll agree that it’s the right choice once you need to change some colours in your web project where you’d need to go through some nasty find-and-replace adventures in your JavaScript files to fix some colour mismatches.

The prebuilt CSS version of Chartist ships with 15 default colours that will be applied to your chart series elements. If you just want to override some of these colours I recommend you use the information found in how to customize the default CSS of Chartist.

The following example illustrates how you’d override the colours of your line chart line and point elements, within the two first sieries (ct-series-a and ct-series-b).

.ct-series-a .ct-line,
.ct-series-a .ct-point {
  stroke: blue;
}

.ct-series-b .ct-line,
.ct-series-b .ct-point {
  stroke: green;
}

Note that on SVG elements there are two CSS properties for colourization. For strokes you should use the stroke property and assign a CSS colour value. For fill areas you can use the fill property. More information can be found in the above topics.

Dynamic colouring

Often, predefined classes which can be used to colour your charts are fine but sometimes CSS is not flexible enough to control all facets of dynamic appearance. While we could build semantic classes like level1, level2, level3 and so on, we could then assign a class dynamically, but still we’d need to rely on discrete values defined in CSS. One lack of CSS today is that it does not incorporate dynamic values like mouse position or placeholder variables that can be linked to JavaScript.

So, how do you go about your heat map chart or dynamically calculated line chart strokes based on your data?

Chartist offers you a powerful tool for such kind of chart manipulations. The intrusive event pipeline of Chartist allows you to hook into a draw event that allows you to modify all your charts elements on the go while they’re drawn.

The following live code example shows you how to make a dynamically coloured chart based on some data. Please go ahead and play around with the example, that’s what live coding is for! For more information on how to use the Chartist.Svg API, please check the API documentation.

Using draw events to modify chart elements

Advanced

In the following chapter you'll find some advanced usage examples that might be of interest for you. Chartist is very flexible because it relies on standard technology. This also means that you will need to implement certain things yourself. This topic should cover some of these use-cases and give you some basic idea why and how to implement certain functionality.

Animations using Chartist.Svg

Usually we recommend using CSS for animations as it's closer to a clean separation of concerns. However, sometimes you would want to animate SVG properties that are not available in CSS to animate. For this purpose we have added a simple but powerful animation API that allows you to create SMIL animations in a more convenient way.

In combination with the draw events of Chartist the animations are a very powerful and flexible tool. You can intercept almost any step in chartist and if there is an SVG element involved you can animate it using Chartist.Svg.animate.

The following simple example shows you how to created a delayed fade in effect for the a scatter chart. You can also edit the example to play around with the settings.

Some SVG Animations can only be done with SMIL

Switching axis type

The default configuration of the line chart is that it will use a step based X-Axis and an automatic linear scale for the Y-Axis. This is all happening under the hood of Chartist and already satisfies a lot of use-cases.

Sometimes though, it's not enough to have a fixed step chart and you'd need something a bit more complex. Something that allows you to plot those values along the X- and Y-Axis, instead of just the Y-Axis. Sometimes, you'd also want to specify the ticks on your chart manually rather than having them auto calculated from Chartist.

Of course Chartist wouldn't let you down with all those ideas you have in mind on how to visualize your data!

A line chart is only 1-dimensional?!

By default, Chartist uses Chartist.StepAxis for the X-Axis and Chartist.AutoScaleAxis for the Y-Axis. Please read the API documentation if you'd like to get more details, or available options on axis configuration.

The step based axis will not use any value for projection but rather rely on the index of the given value to determine the position. This is fine for discrete steps of one dimensional data, like we know it from regular Chartist charts:

var data = {
  labels: ['A', 'B', 'C'],
  series: [[10, 8, 14]]
};

What really happens with such one dimensional series data under the hood is that it will be transformed into two dimensional data like so:

var data = {
  labels: ['A', 'B', 'C'],
  series: [[
    {x: undefined, y: 10},
    {x: undefined, y: 8},
    {x: undefined, y: 14}
  ]]
};

You can see that Chartist will automatically convert one dimensional data into two dimensional values where the previous value is assigned to y and x will be set to undefined. As the default axis for projecting the x value is a Chartist.StepAxis that relies on the value index rather than the value, this is perfectly fine for the default setup.

Creating an XY-plot chart

In order to plot on the X-Axis too, we'd need to switch the standard axis type Chartist.StepAxis to something more continuous. Let's create a full fledged auto scale chart that scales both the Y- and X-Axis automatically using the Chartist.AutoScaleAxis!

Configure your axis type

A few things are different in this chart. Because the labels array of our data is just used to be mapped as ticks option for the default Chartist.StepAxis X-Axis, we can completely remove the labels from our data, once we use a different axis than the step based one. Also you can see now from the data series is that we are specifying 2-dimensional values directly.

Fixed stuff can be sweet too!

The following example shows how to create an axis with some fixed ticks. The Chartist.FixedScaleAxis can be used to create a more rudimentary continuous linear scale, where ticks can be fixed either with an array of values or with a divisor. For the detailed options please check the API documentation.

Unleash your creativity...