Integration of Plotly in Reactjs

While developing a website sometimes we need to handle large amounts of data and need to show in such a manner users can understand it easily. In data visualization, we take information or data and represent it in a visual format like maps and graphs. Due to graph representation it’s easier to understand the patterns, trends, and visualize the data.
The main reason to use the graph is to represent the data that is too numerous and difficult to show easily in text and in small space.

Commonly used libraries

A lot of time we need to add different types of graphs to represent the data. There are multiple libraries used to represent the graph. The most commonly used libraries are:
  1. Chart.js
  2. Victory
  3. Plotly.js
  4. Highcharts
  5. nvd3. 
  6. C3.js
  7. Chartist
In this article, I will explain how to integrate plotly.js and generate graphs for our website using Reactjs.

Overview of Plotly

Built on top of d3.js and stack.gl, plotly.js is a high-level, declarative charting library. plotly.js ships with over 40 chart types, including scientific charts, 3D graphs, statistical charts, SVG maps, financial charts, and more.
Plotly is an open-source Javascript library used to draw charts. For react we use the react-plotly.js library with plotly.js.
The data for the Plotly.js graph is a JSON object. Every attribute like color, grids, data has a respective JSON object.
In plotly graph description groups attributes into two sections:

Traces

Plotly supports different traces types like scatter, bar, pie, line charts, etc. Every trace has some common keys and additional extra keys depending on the type of the trace.
For example,
data={[

          {

            x: [1, 2, 3],

            y: [2, 6, 3],

            type: "scatter",

            mode: "lines+markers",

            marker: { color: "red" },

          },

          { type: "bar", x: [1, 2, 3], y: [2, 5, 3] },

        ]}
Here we discuss some keys of traces objects,
TypeThe type key is the type of graph we want to represent. Here in the above example, we used bar and scatter type.
Name It is the trace name. This name shows on hover and to the legend item.
Visible It decides the trace is visible or not. It has 3 values true, false, legendonly“.The default value is true. If legendonlythen it does not appear on the graph but when we click on legend then it showed.
Showlegend It determines the legends are shown or not. By default its value is true.
Opacity It sets the opacity of the trace. It lies between or equal to the 0 and 1.
Mode It shows the drawing mode for the traces of type scatter. It is a combination of strings “lines”,”markers”,”text” that joined with + or “none”.
For example, “lines+markers”
x It represents the x coordinates. The values of these keys are data arrays.
y It represents the y coordinates. The values of these keys are data arrays.
x0 and dx It is an alternative to the x key. The default value is 0. It is the starting point for x coordinates, used with dx key.dx key represents steps to increment the value of x coordinates. The default value of dx key is 1.
y0 and dy It is an alternative to the y key. It works similarly for y coordinate as x0 and dx work for x coordinate.
To know more about traces visit https://plotly.com/javascript/reference/#scatter

Layout

On the Branch.io dashboard create your account,use link https://dashboard.branch.io/login. After the account was created, set up an account for android.
Title It represents the title of the graph.we can use it as an object with one or more keys. The keys are text, font, pad, etc.
Legend It is used to decorate the legends.This object containing keys like bgcolor, bordercolor, borderwidth, font, etc.
Margin This attribute is used to set the margin to the graph. It has keys like t(top),b(bottom),l(left),r(right), pad, autoexpand, etc.
There more attributes of layout like size, fonts, colors, etc To know more about it you can refer https://plotly.com/javascript/reference/#layout-title
Examples
First, we install Plot.ly in our project using npm,
npm install react-plotly.js plotly.js --save 
After that, we will import the Plot component and pass the attributes as per our graph requirement.

Creating a Bar Chart with Scatter

import React from "react";

import Plot from "react-plotly.js";

class Graph extends React.Component {

  render() {

    return (

      <Plot

        data={[

          {

            x: [1, 2, 3],

            y: [2, 6, 3],

            type: "scatter",

            mode: "lines+markers",

            marker: { color: "red" },

          },

          { type: "bar", x: [1, 2, 3], y: [2, 5, 3] },

        ]}

        layout={{ width: 320, height: 240, title: "Graph Example" }}

      />

    );

  }

}

export default Graph;

Bar Chart
In plotly everything passed to an attribute is in JSON object format. In the above example, we created a simple bar chart with scatter.
In data, we added two objects which result in a combination of two graphs i.e bar and scatter. This is a simple example where we directly pass the props to the component.

Basic Pie Chart

import React from "react";

import Plot from "react-plotly.js";

class Graph extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      data: [{

        values: [19, 26, 55],

        labels: ['Residential', 'Non-Residential', 'Utility'],

        type: 'pie'

      }],




      layout: {

        height: 400,

        width: 500,

        title: "Pie chart"

      }




    };

  }

  render() {

    return (

      <div style={{ width: "100%", height: "100%" }}>

        <Plot

          data={this.state.data}

          layout={this.state.layout}

          onInitialized={(figure) => this.setState(figure)}

          onUpdate={(figure) => this.setState(figure)}

        />

      </div>

    );

  }

}

export default Graph;
Pie Chart

Area Chart

import React from "react";

import Plot from "react-plotly.js";




class Graph extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      data: [

        {

          x: [1, 2, 3, 4],

          y: [0, 2, 3, 5],

          fill: 'tozeroy',

          type: 'scatter',

          name: 'Vendor'

        },




        {

          x: [1, 2, 3, 4],

          y: [3, 5, 1, 7],

          fill: 'tonexty',

          type: 'scatter',

          name: 'Provider'

        }],




      layout: {

        height: 400,

        width: 600,

        title: "Area chart"

      }




    };

  }

  render() {

    return (

      <div style={{ width: "100%", height: "100%" }}>

        <Plot

          data={this.state.data}

          layout={this.state.layout}

          onInitialized={(figure) => this.setState(figure)}

          onUpdate={(figure) => this.setState(figure)}

        />

      </div>

    );

  }

}

export default Graph;
Area Chart

State Management

This component does not merge its internal state with any updates. When a user interacts with the plot by zoom or other actions and after that if the component re-renders then it loses this information. So using onUpdate callback prop we capture and upstream that information.
In ReactJS we can use state and props to get better results. So we can change the data dynamically by updating the state of the parent component.
import React from "react";

import Plot from "react-plotly.js";




class Graph extends React.Component {

  constructor(props) {

    super(props);

    this.state = {

      data: [

        {

          x: [1, 2, 3],

          y: [2, 6, 3],

          type: "scatter",

          name: "scatter",

          //   visible: "legendonly",

          mode: "lines+markers",

          opacity: 0.1,

          marker: { color: "red" },

        },

        { type: "bar", name: "bar", x: [1, 2, 3], y: [2, 5, 3] },

      ],

      layout: { width: 600, height: 500, title: "Graph eaxmple" },

    };

  }

  render() {

    return (

      <div style={{ width: "100%", height: "100%" }}>

        <Plot

          data={this.state.data}

          layout={this.state.layout}

          onInitialized={(figure) => this.setState(figure)}

          onUpdate={(figure) => this.setState(figure)}

        />




      </div>

    );

  }

}

export default Graph;
We can create different types of the graph using plotly.js and also customize the graph as per our requirement.

subscribe to our newsletter

   
   
Poonam Nalawade
Poonam is a full-stack developer with around 1+ years of experience in developing web applications. She has good knowledge of ReactJs, Javascript and Python Django framework. She is having experience in creating REST APIs, developing web applications using python and react. She loves to solve technical problems.
Related Posts

Leave a Comment