DEV Community

Cover image for How to Create a Line Chart in React with SciChart
Andrew Bt
Andrew Bt

Posted on

How to Create a Line Chart in React with SciChart

When building a line chart, your brief may require more than just conveying the information in a graphical format. There may be a requirement for the data to be displayed with custom colours, as part of a dashboard, or to ensure dynamic rendering to keep up with the input of a 24/7 data source.

We'll guide you through the process of creating dynamic and insightful line charts using React and SciChart. Learn how to set up, customise and add interactivity to your charts for a richer user experience that helps users effortlessly find the insights they're searching for.

Why a React Line Chart?

From prices to vital signs, line charts make visualising trends across time series and sequential data accessible for many sectors and use cases.

Financial dashboards commonly use React-powered line charts to plot time-series market data and performance metrics.

In the oil and gas industry, React line charts support the monitoring of well data, process variables and IoT sensor streams. It's not uncommon for a React-based Oil & Gas Explorer demo to display multiple line charts of well log curves (gamma-ray, resistivity, porosity logs, etc.) in a synchronised dashboard.

Line charts are also at the forefront of healthcare. Line charts in hospital analytics dashboards are an effective way to communicate daily hospital admissions over time and clearly display changes in demand for hospital beds. With the rise of wearable tech, fitness app users also want to view their step count or heart rate over a period of time.

This information has many applications, such as improving patient experiences in hospitals and making health conditions easier to manage.

Setting Up Your Project

Your true north should always be to read the documentation first. However, if you prefer to get started with visual support, we recommend looking at the examples and demos.

Whichever sector you're building your React line chart for, we'll show you how to set up a project with SciChart-React. This sets the foundation for building your chart. From there, you can add the more fun elements that make the look and feel of the chart both fully customised and high-performance.

Initialising an npm project

npm init -y
npm install scichart scichart-react
npm install --save-dev webpack
npm install --save-dev webpack-dev-server
npm install --save-dev webpack-cli
npm install --save-dev copy-webpack-plugin
Enter fullscreen mode Exit fullscreen mode

Creating a Line Chart with SciChart

Use the SciChart component to render your first chart. The code below demonstrates how to create a line chart using an initChart function. This function initialises a SciChart surface, sets up X and Y axes, generates sample data and associates it with a line series. The chart is then added to the SciChart surface.

import { SciChartReact } from "scichart-react";
import {
  SciChartSurface,
  NumericAxis,
  FastLineRenderableSeries,
  XyDataSeries,
} from "scichart";

const initChart = async (rootElement: string | HTMLDivElement) => {
  const { sciChartSurface, wasmContext } = await SciChartSurface.create(rootElement);

  sciChartSurface.xAxes.add(new NumericAxis(wasmContext));
  sciChartSurface.yAxes.add(new NumericAxis(wasmContext));

  const xValues = Array.from({ length: 100 }, (_, i) => i);
  const yValues = xValues.map((x) => Math.sin(x * 0.1));

  sciChartSurface.renderableSeries.add(
    new FastLineRenderableSeries(wasmContext, {
      dataSeries: new XyDataSeries(wasmContext, { xValues, yValues }),
      stroke: "#50C7E0",
      strokeThickness: 2,
    })
  );

  return { sciChartSurface };
};

export const LineChart = () => (
  <SciChartReact initChart={initChart} style={{ width: 800, height: 400 }} />
);
Enter fullscreen mode Exit fullscreen mode

As your first port of call, we recommend reading through Tutorial 01 and Tutorial 02 (linked below), as these show you how to get set up and add your data.

Useful Resources

Available modifications of line charts include:

What Language Should You Use to Build Your React Line Chart?

Our top tip for building React line charts is to use TypeScript rather than JavaScript. For example, when setting a property on an X axis in the code editor, TypeScript support makes it easier to see documentation and catch typos. With JavaScript, typos may not be noticed until much later. This makes the project harder to maintain and can take more time to get over the line.

If you want to create a simple chart, you can use JSON with our Builder API. This is similar to other JavaScript chart libraries, so if you're new to SciChart, the learning curve will be negligible.

SciChart React line chart demo
SciChart React Line Chart Demo

Useful Resources

Customising Your React Line Chart

When creating a line chart, there are several APIs you should refer to, including the Axis API, Annotations API and ChartModifier API. The latter is required to add interactions. In GitHub, you can easily work your way down the list of properties, covering everything from styling and theming to accessibility, which shows you how to add voiceovers, keyboard accessibility and colour contrast. See what is possible with SciChart React charts by exploring our APIs.

SciChart supports tens of thousands of properties for customisation. These cover visual design as well as interactivity and annotations that help end users engage more with the finished React line chart. Below are some of the more common customisations, including adding multiple axes and applying zooming and panning.

Multi-Axis Line Chart

Supporting unlimited axes opens up plenty of possibilities. Adding a second axis to a SciChartSurface works much the same as adding one, with one difference: you must assign a unique string ID to every axis via the axis.id property when there is more than one. In version 4, this behaviour changes and IDs are auto-generated.

After adding an axis, you can use axis.id to link it to series, annotations and chart modifiers. To place an axis on either side of a chart, set axis.axisAlignment to a value of EAxisAlignment (for example EAxisAlignment.Left or EAxisAlignment.Right).

👉 View the tutorial

Zooming and Panning

In SciChart, chart interactions are defined by ChartModifiers. As well as the built-in modifiers, you can write custom modifiers or extend existing ones.

The provided modifiers include RubberBandXyZoomModifier, ZoomPanModifier, ZoomExtentsModifier, MouseWheelZoomModifier and more.

Tooltips and Hover Effects

Tooltips and hover effects offer a better user experience. Discover how to add them by watching the step-by-step video tutorial above. Annotation options include an onHover callback and a hover modifier, which let you add tooltips or get notified when a user hovers over an annotation.

This helps your organisation understand how end users interact with your data visualisation and see what interests them versus what gets ignored. Try it for yourself with our Hover Annotations Documentation.

Reliable Performance for Large Datasets

Line charts are not complex. The problem comes when you're trying to draw 100,000 or 1 million lines. Most libraries without hardware acceleration will fail to support this many.

For smoother performance, we recommend WebGL rendering over 2D canvas rendering. The beauty of WebGL is that computationally intensive tasks, such as rendering 3D charts or matrix transformations, are processed on the GPU instead of the CPU, which is much faster thanks to parallel computing.

The result is a more performant and reliable React line chart. With a responsive, GPU-based React chart library, data populates in real time and the chart updates automatically whenever the data source collects new material, so end users always see the most up-to-date information.

A cross-platform chart library also ensures charts work across platforms and devices without lag or slowdown. This is useful for organisations that rely on multiple devices to communicate the same information, giving a consistent experience and reducing user frustration.

Getting the Support You Need as Quickly as Possible

Building basic line charts shouldn't require much of a learning curve. However, if you hit an obstacle with chart creation or rendering performance, you'll want support quickly.

SciChart offers a responsive support service, and there are ways to speed things up. Create a minimal project that reproduces the problem and share it with our developer team. A runnable source project or CodePen example is far more useful than isolated snippets of code, leading to quicker diagnosis and fewer back-and-forth iterations.

Next Steps for Building High-Performance Line Charts

scichart-react is a free, open-source React chart component for use with SciChart.js. It simplifies the development of React charts by handling initialisation, deletion and the lifecycle of the chart, and supports multiple approaches from simple to advanced setups.

Unlock the power of data visualisation in your React applications with SciChart, a high-performance charting library. For further customisation, we recommend exploring our documentation.

Top comments (0)