LightningChart JSCreating a JavaScript Donut Chart

TutorialPerfect tutorial for beginners to start creating charting applications using a Donut chart as example.

JavaScript Donut Chart

Hi again!

In this article, we’ll be doing a simple yet extremely useful donut chart. For this example, we’ll use the LightningChart JS library and the pie chart component. A donut chart is basically a variation of a pie chart divided into segments representing a category.

The size of each category is proportional to its percentage and is easily identified by the color codes. Visually, the donut chart does not have a center compared to a pie chart.

Key aspects of donut charts

  • Donut charts must have clear labels and preferably, avoid visualizing too many categories in one chart as it may become difficult to understand.
  • The size of the inner and outer rings of the chart should be carefully chosen to ensure that the chart is easy to read and interpret. If the inner ring is too small, for example, the labels may be difficult to read, while if the outer ring is too large, the chart may become cluttered and difficult to interpret.
  • Colors should be used to clearly distinguish between different sections of the chart, but should also be chosen carefully to avoid overwhelming the viewer.
  • Donut charts are most effective when used to display a small number of data points.

This is a very intuitive tutorial so let’s start.

Project Overview

You can interact with the donut chart. Notice that the chart will be fully customizable throughout the tutorial, so the look and feeling can be adjusted to your own liking.

zip icon
Download the project to follow the tutorial

Local Setup

1. Download the initial template that will help us get started with this example.

2. After downloading the template, you’ll see a file tree like this:

javascript-refreshing-spectrum-chart-file-tree

3. Open a new terminal and run the npm install command:

As usual in a NodeJS project, you need to run the npm install command. That would be everything for our initial setup. Let’s code.

CHART.ts

Inside this file, we will have all the logic needed to create our chart, configure animations, and format the data.

1. Declare the constant lcjs that will refer to our @arction/lcjs library.

const lcjs = require('@arction/lcjs')

2. Extract required classes from lcjs

const {
    lightningChart,
    PieChartTypes,
    UIElementBuilders,
    LegendBoxBuilders,
    UIDraggingModes,
    SliceLabelFormatters,
    UIOrigins,
    emptyFill,
    emptyLine,
    Themes,
} = lcjs

3. Creating the chart object

const donut = lightningChart()
    .Pie({
        theme: Themes.cyberSpace,
        type: PieChartTypes.LabelsInsideSlices,
    })
    .setTitle('Inter Hotels - hotel visitors in June 2016')
    .setPadding({ top: 40 })
    .setMultipleSliceExplosion(false)
    // Style as "Donut Chart"
    .setInnerRadius(60)
Let’s review some parameters:

setPadding: refers to the padding size for the left/right side.

setTitle:  This determines the text that will be shown as the top title in the dashboard.

Theme: LightningChart has developed a collection of themes. To see the full list, visit the Themes documentation.

LabelInsideSlices: this will set up the labels inside each proportion. Consider that this works better when the label text is short and you don’t have many slices in your donut chart (compared to a normal pie chart with more space).

setMultipleSliceExplosionsets whether multiple slices are allowed to ‘explode’ at the same time or not. When a slice is exploded, it is drawn differently than the unexploded state.

setInnerRadiusdefines the inner radius of the pie chart. This is a method that can be used to style the chart as a donut chart with a hollow center.

4. Creating the data object

const data = {
    country: ['US', 'Canada', 'Greece', 'UK', 'Finland', 'Denmark'],
    values: [15000, 20030, 8237, 16790, 9842, 4300],
}

We’ll make a JSON object to display the data in our chart. For a donut type of chart, the JSON structure is simple and as you can see, we will need an array of categories. The categories will be, for instance, the countries. Additionally, create another array with the values of each category.

5. Formatting the data

const processedData = []
let totalVisitor = 0
for (let i = 0; i < data.values.length; i++) {
    totalVisitor += data.values[i]
    processedData.push({ name: `${data.country[i]}`, value: data.values[i] })
}

To create a slice for the donut chart, we need to unite the country array together to the value array within the same object. [{Country,Value}], one object per country.

TotalVisitor will be the sum of all the values and it will be shown as a total in the center of the chart.

6. Adding the slices

donut
    .addLegendBox(LegendBoxBuilders.HorizontalLegendBox)
    // Dispose example UI elements automatically if they take too much space. This is to avoid bad UI on mobile / etc. devices.
    .setAutoDispose({
        type: 'max-width',
        maxWidth: 0.8,
    })
    .add(donut)
For the setAutoDispose property, it will dispose of an example of UI elements automatically if they take up too much space. This will avoid a bad UI experience on mobile devices.

For LegendBoxBuilders, this will be a collection of available LegendBox builders. To build them, you must pass one of these to the method addLegendBox(). This method can be accessed through the charts, dashboard, etc.

7. Adding the total textbox

donut
    .addUIElement(UIElementBuilders.TextBox)
    .setPosition({ x: 50, y: 50 })
    .setOrigin(UIOrigins.CenterTop)
    .setDraggingMode(UIDraggingModes.notDraggable)
    .setMargin(5)
    .setTextFont((fontSettings) => fontSettings.setSize(25))
    .setText(`Total: ${totalVisitor} visitors`)
    .setBackground((background) => background.setFillStyle(emptyFill).setStrokeStyle(emptyLine))

Notice that you can add text boxes to the donut chart. For instance, the total value could be centered in the chart categories. As for other properties:

  • addUIElement will add a standalone UIElement using a builder.
  • setPosition will establish a position for this UIElement relative to its origin.
  • setDraggingMode will set the dragging mode of the object and it will define how the object can be dragged by the user with the mouse.
  • setMargin will establish the margin around the object using pixels as measurement.
  • setTextFont defines the label font.
  • setText defines the text of the label.
  • setBackground is a method for mutating the Background of the object.
  • setFillStyle defines the fillStyle of the Background.
  • setStrokeStyle defines the stroke style of the Background.

Conclusion

To run your chart, you’ll have to execute the npm start command, click on the local host path, and visualize the donut chart in your browser as follows:

donutChart

The development of this chart was very intuitive and easy. Whether you’re new to charting or a charting wizard, I recommend you use this tutorial for creating your own custom donut charts. As well, the template provided in this article can be fully adjusted to your liking.

See you in the next article!

Omar Urbano Software Engineer

Omar Urbano

Software Engineer

LinkedIn icon
divider-light

Continue learning with LightningChart