Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Charting With React Using jQWidgets

DZone 's Guide to

Charting With React Using jQWidgets

You've got your findings, now you need to visualize and present them. Learn how with these two JavaScript libraries.

· Big Data Zone ·
Free Resource

Charts are an integral part of a site's ability to represent data. Data collected through a website or any business data can be represented using charts. A chart makes data readable and increases its clarity. Different types of charts are used for various data. This article is about using the jQWidgets chart component for React. We'll show you how to integrate the charts and different charts with its features.

The chart component for React is light weight with advanced features. It makes it easy to add animations and responsive charts to your site. Before we start with charts we need to install React and Node.js.

Installing React

React is a responsive and interactive framework which renders the right components while the data changes.

Install Node.js 8.10 or later. Check for Node.js and npm versions.

Create React App

To create an application using React, use the following command. This creates the folder structure and the directory called my-app. Once my-app is created, cd to my-app and type npm start. The project opens in http://localhost:3000.

npm i -g create-jqwidgets-react-app
create-jqwidgets-react-app my-app
cd my-app
npm start

The folder structure is shown below:

Folder structure

Create an assets folder in the src folder. Add jqwidgets and jqwidgets-react folders inside the assets folder.

Below is the src folder structure with assets and app.js file.

src folder structure

Create a Simple jQWidgets React Chart Component

We will take a glimpse at setting chart, configuration, and imports for using jQWidgets's React charts.

App.js file

We need to import JqxChart from jqwidgets-react.

import JqxChart, { IChartProps, jqx } from 'jqwidgets-scripts/jqwidgets-react-tsx/jqxchart'

Creating the component class using JQXChart, set the properties to chart. Note the name of the chart is myChart.

class App extends React.PureComponent<{}, IState> {
private myChart = React.createRef<JqxChart>();
  render () {
// …
    return (
        <JqxChart ref={this.myChart}
            style={{ width: 500, height: 500 }}
            showLegend={true} enableAnimations={true}
            source={dataAdapter} xAxis={xAxis}
            valueAxis={valueAxis} seriesGroups={seriesGroups}
        />
    )
// …
  }
}

Render the class in the HTML element of index.js.

ReactDOM.render( , document.getElementById('app'));

Setting Chart Properties

All the properties set in JqxChart are defined in React properties.

Creating a Chart component

Set the properties, like source, data adapter, and settings for the axis.

// …
let source =
    { // defining the source 
        datatype: "csv",
        datafields: [
            { name: 'ID' },
            { name: 'Year' },
            { name: 'Rate' }
        ],
        url: 'sampledata/sample.txt'
    };

    let dataAdapter = new $.jqx.dataAdapter(source, { async: false, autoBind: true, loadError: (xhr, status, error) => { alert('Error loading "' + source.url + '" : ' + error); } });

    let year = ['2010', '2011', '2012', '2013', '2014', '2015', '2016'];

    let padding = { left: 10, top: 5, right: 10, bottom: 5 };

    let titlePadding = { left: 50, top: 0, right: 0, bottom: 10 };
… //

Set the properties of the x-axis. This contains properties like min and max values, tick marks, labels, etc. You can even set the values for grid lines and the color for grid lines. Other properties like unitInterval and valuesOfTicks can be set.

let xAxis = {
  dataField: "ID",
  formatFunction: function(value) {
    return (
      value.getDate() +
      "-" +
      year[value.getFullYear()] +
      "-" +
      value.getFullYear()
    );
  },
  type: "ID",
  baseUnit: "year",
  valuesOnTicks: true,
  minValue: "2010",
  maxValue: "2016",
  tickMarks: {
    visible: true,
    interval: 1
  },
  unitInterval: 1,
  gridLines: {
    visible: true,
    interval: 3
  },
  labels: {
    angle: -45,
    rotationPoint: "topright",
    offset: { x: 0, y: -25 }
  }
};

let valueAxis = {
  visible: true,
  title: { text: "Closing Price<br>" }
};

Set the seriesGroup, it defines the type of chart and datafields.

let seriesGroups =
    [
        {
            type: 'line',
            series: [
                  { dataField: Year', displayText: 'Year' },
                 { dataField: Rate, displayText: Rate }
           ]
        }
    ];

The above settings will define the chart in React using jQWidgets. Below is the example of a line chart.

Line Chart with React.js

There are different types of charts/series. Line series, bubble series, pie series, etc. We can also have multiple series. We will take a look at different settings for different types of charts. Also, we will look at additional features which can enhance our chart display.

Types of Charts

1. Column and Bar Charts: It displays the size of the measured data. We need to set the type of the chart as a column. While rendering, we can set the columnSeriesOverlap option. By setting this to false, the columns will not overlap with each other. You can set the title padding and animations while displaying the chart.

Below is the example of a series group, using line and column charts. Each series will have its type and properties define.

seriesGroups: [
  {
      series: [
          { dataField: 'GDP', displayText: 'GDP per Capita' },
          { dataField: 'Debt', displayText: 'Debt per Capita' }
      ],
      type: 'column',
      valueAxis:
      {
          title: { text: 'GDP & Debt per Capita($)<br>' },
          unitInterval: 5000,
          visible: true
      }
  },
  {
      series: [
          { dataField: 'DebtPercent', displayText: 'Debt (% of GDP)' }
      ],
      type: 'line',
      valueAxis:
      {
          gridLines: { visible: false },
          labels: { horizontalAlignment: 'left' },
          position: 'right',
          title: { text: 'Debt (% of GDP)' },
          unitInterval: 10,
          visible: true
      }
  }
],

Also, to enable animations, set enableAnimations to true.

enableAnimations={true}

Data visualization

There are various column charts like stacked columns, bar series, and column range series, where each column is displayed in the range of data in a y-axis. You can have columns with negative values and conditional colors.

2. Pie and Donut Series: It is used to show the relative size of the measured data. The SeriesGroup is set to pie, we need to set initialAngleradius, and labelRadius. Below are the series settings for the pie chart.

series: [
  {
      centerOffset: 0,
      dataField: 'Share',
        displayText: 'Browser',
        formatSettings: { sufix: '%', decimalPlaces: 1 },
      initialAngle: 10,
      innerRadius: 90,
      labelRadius: 120,
      radius: 130
  }
],

There are partial pie series, which display the pie charts partially. To display a partial pie chart, set the endAngle property to 180. You can also have donut charts by setting the type of seriesGroup as donut. For donut charts, a radius and inner radius need to be set.

Data visualization

3. Polar Series: This series is used when you have data with multiple variables on a two-dimensional area. Different shapes are displayed according to data. You need to set the radius and polar properties as true.

Data visualization

You can set the color combinations for the data represented and the series type, which are in various forms like spline, column, scatter, spline area, etc.

4. Multiple Series Type: We can have multiple series of types in the same chart. The below chart represents the spline area and stacked columns.

Data visualizations

Extra Features

  1. Charts can be used for live updates. For charts with live updates, we can set time in seconds, select color schemes, and set the alignment with a series type.

  2. We can have color bands for the x-axis, which is set by the typerangecolumn. We can set the minimum and maximum value of the x-axis using the color range.

  3. Customization of chart annotations with color, offset, and values.

  4. We can set width and height in percentage; also, custom drawings can be made using the style and grid lines.

  5. Charts can be easily integrated with grid and tabs, and features like export and print can be easily used.

  6. Charts can be easily styled. These styling features make the chart more readable and user-friendly.

Summary

A chart component of jQWidgets for React is light weight and easily configurable. It has various charts and features for enhancing the charts.

Topics:
javascript ,javascript api ,react.js ,big data ,data visualization tutorial

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}