LightningChart JSCreate a JavaScript Pie Chart with NodeJS, TypeScript & LightningChart

TutorialStep-by-step tutorial how to create a high-performance & interactive pie chart with LightningChart JS.

JavaScript Pie Chart with NodeJS & TypeScript  

Today, we are going to do a short tutorial on how to generate a pie chart using Node JS, TypeScript, and LigningCharts JS. To see how to get LightningChart JS for free, visit the Community license page.

LightningChart is an API focused on data representation, using a wide variety of charts (2D and 3D), with an intuitive implementation and wide compatibility with various development platforms.

There are currently two solutions for developing with LightingCharts.

  • LightningChart .NET for desktop applications (supports WPF, UWP, and WinForms)
  • LightningChart JS for web, mobile, and desktop applications.

TypeScript is the intended framework for development with LightningChart JS, so the implementation under this programming language is strongly recommended.

To carry out this tutorial, it is recommended to have a minimum of experience in the use of Node JS and Visual Studio Code.

“From my point of view, the use of technologies such as Node JS and TypeScript is becoming more and more common in mobile application and web development. They are highly versatile technologies that allow easy implementation of plugins and APIs”.

Before starting, it is necessary to have a development platform that allows us to edit javascript and typescript files. For this example, we will use Visual Studio Code. In the case Node JS is not installed. The installation will be required (It is highly recommended to have the latest version of Node JS):

https://nodejs.org/en/

Given the brief introduction, let’s get started.

Project Overview

Feel free to interact with the JavaScript pie chart you’ll create. Also, make sure to download the project to follow the tutorial.

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, we will open the entire folder in Visual Studio Code:

javascript-pie-chart-project-setup

Note: If you are not yet familiar with projects like Node JS; Inside these projects, you will find a file called: package.json. The package.json file will contain a list of all the dependencies or libraries that are necessary to run the project. This is done with the goal of not having to download a project with all its dependencies stored in the “node_modules” folder.

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

Open-a-new-terminal-in-Visual-Studio-Code
Run-NPM-install-command

After executing that command, we will see a series of downloads in the terminal. If we check our file explorer, we will see that a folder named “node_modules” was created. This folder will contain all the files corresponding to each dependency specified in our “package.json” file.

Data Source

1. Having made the initial setup of our project, we will begin to create our data.

For this example, we will create a “JSON” file, which will contain the data that will be displayed in our LightningChart.

Creating-a-JSON-file-with-the-data-for-the-pie-chart

We will right-click on the “src” folder, and select the “New File” option. In my case, I decided to name my file:

Renaming-the-JSON-file-with-the-data

For your project, you can call it whatever you see fit. You will only have to replace the name “cities” with the name of your file(in all the code) and everything should work correctly. 

In our new file, we will write the following JSON structure (you can add more members with your own values):

{
   "chartName": "Cities from Finland",
   "members":[
   {
       "name":"Helsinki",
       "population": 1305893,
       "id":"FN101"
   },
   {   
       "name":"Tampere",
       "population": 341696,
       "id":"FN102"
   }
]}

2. Now, open the “tsconfig.json” file. We have to add the following line:

{
   "compilerOptions": {
                 "outDir": "./dist",
      "module": "commonjs",
                 "target": "es5",
                 "esModuleInterop": true,
                 "resolveJsonModule": true,
      "lib": [
          "es2015",
                            "dom"
                ]    }
}

The “resolveJsonModule” option allows us to import JSON modules into TypeScript modules.

Pie Chart

1. We will now start coding our LightningChart chart. Open the file “PieChart.ts” and import our JSON file:

//Import data json file
import city from './cities.json';

2. Import the LightningChart JS library:

// Import LightningChartJS
Const lcjs = require('@arction/lcjs')

Note: The @arction/lcjs library was downloaded during the initial setup of our project. This will be located inside the [node_modules/@arction] folder.

We will import the LightningChart collections, so they can be used in our pie chart:

//Extract required properties from LightningChartJS
   const {
                 LightningChart,
      PieChartTypes,
                 LegendBoxBuilders,
                 SliceLabelFormatters,               
      Themes
   } = lcjs
PieChartTypes=Collection of PieChart implementations. Each option can have its own visual design and API for customization of it. 

LegendBoxBuilders=Collection of available LegendBoxBuilders. To build LegendBoxes you must pass one of these to the method: addLegendBox(). 

SliceLabelFormatters= It allows us to give custom formatting to the labels within the chart. 

Themes= Collection of pre-designed themes. These themes have their own color palette and other graphical interface properties. 

For more information, please visit the LightningChart JS API documentation.

3. Now we will add a short condition:

“If the window resolution is wide enough, the pie chart with outer labels will be selected, otherwise, they will be displayed within each slice.”

const pieType = window.innerWidth > 599 ? PieChartTypes.LabelsOnSides : PieChartTypes.LabelsInsideSlices

4. It’s time to create our instance of the pie chart.

Inside our object, we will assign the type of chart (in this case “PieType”) and the theme of our chart. In the Title value, we can directly write the title of our graph.

For this example, I am taking the “ChartName” node located within our JSON file. 

To access this node, we use the “city” object, which was created by importing our JSON file, at the beginning of our code.

const pie = lightningChart().Pie({
   theme: Themes.darkGreen ,
   type: pieType
})

   .setTitle(city.chartName)
   .setAnimationsEnabled(true)
   .setMultipleSliceExplosion(true)
For this example, I decided to use the “Dark Green” theme, but LightningChart gives us a wide variety of themes, and it is only necessary to type the name of the theme.

Finally, we assign the value “true” to the animations of our chart. To see a list of all themes, you can go here: Themes

5. To finish,  we will assign the values to the labels of our graph:

// Select json data
const data = city.members

// ----- Create Slices -----
const slices = data.map((item) => pie.addSlice(item.id+'-'+item.name, item.population))

// Specify function which generates text for Slice Labels(LabelFormatter).
pie.setLabelFormatter(SliceLabelFormatters.NamePlusRelativeValue)

// ----- Add LegendBox -----
pie.addLegendBox(LegendBoxBuilders.VerticalLegendBox)

// 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.30,

})
.add(pie)

If you remember, the “city” object refers to our JSON file, so we assign the members array to the data variable. That way, we will be able to access all the nodes located inside members.

In the slices constant, we will create a slide for each section added within members. The .map function will execute the addSlice function for each member.

Inside addSlice, two values must be assigned: the tag value and the numeric value used to calculate the size of each slide.

Finally, the labels are formatted, and the legend box is added. This box is assigned the width and it is specified to which graph it corresponds.

6. Finally, we will execute the npm_start command.

We will see how our project is compiled:

LightningChart-and-NodeJS-pieChart-project-compiled

If we hold down the control key and click on the path where our project is running, our default browser will open, and we can see the result:

PieChart-created-with-LightningChart-JS-and-NodeJS

Within the JavaScript pie chart, we can interact with each of the objects, generating an animation that will help us better to understand the information displayed.

FAQs

When to use a JavaScript pie chart?

A pie chart can be used when comparing a few segments displayed as a percentage. Each of the slices is proportional to its quantity. This interactive example allows users to isolate segments of the pie chart (exploded pie chart) to emphasize a category or value.

What is LightningChart JS?

LightningChart JS is an advanced data visualization library that can be easily integrated into web, mobile, and desktop applications that need to render millions or billions of data points at the highest performance.

What other charts can I create with LightningChart JS?

There are more than 100 chart types that can be created with LightningChart JS, including 2D and 3D, you can visit our interactive examples to see more.

Is LightningChart JS free?

LightnignChart JS offers both non-commercial and commercial licenses. If you want to use the library for free for non-commercial purposes, get the Community license.

LightningChart JS

LightningChart JS is an advanced JavaScript charting library featuring 100+ charts that can be easily integrated into cross-platform applications that demand high-performance charts with fast rendering and large dataset processing of several billions of data points. 

Omar Urbano Software Engineer

Omar Urbano

Software Engineer

LinkedIn icon
divider-light

Continue learning with LightningChart