How to Integrate 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.

Check Out What It Takes To Build A Successful App Here

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,

Type – The 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 “legendonly” then 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”
 It represents the x coordinates. The values of these keys are data arrays.
 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 a y key. It works similarly for y coordinate as x0 and dx work for x coordinate.
To know more about traces visit- JavaSript Figure Reference

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

We Worked With Insurance Benefit Startup To Augment Their Development Team and Accelerate the Development

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;


Integration-of-Plotly Bar

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
Pie

 

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
area

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 the 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 graphs using plotly.js and also customize the graph as per our requirement.

coma

Conclusion

In this article, we learn that we can create different types of graphs using plotly.js and also customize the graph as per our requirement. If you more suggestions on these please comment us.

Hire Our Experienced Full Stack React.js Developers to Meet Your Business Requirements.

Poonam Nalawade

Tech Expert

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.

Get in touch for a detailed discussion.

Hear From Our 100+ Customers
coma

Mindbowser helped us build an awesome iOS app to bring balance to people’s lives.

author
ADDIE WOOTTEN
CEO, SMILINGMIND
coma

We had very close go live timeline and MindBowser team got us live a month before.

author
Shaz Khan
CEO, BuyNow WorldWide
coma

They were a very responsive team! Extremely easy to communicate and work with!

author
Kristen M.
Founder & CEO, TotTech
coma

We’ve had very little-to-no hiccups at all—it’s been a really pleasurable experience.

author
Chacko Thomas
Co-Founder, TEAM8s
coma

Mindbowser is one of the reasons that our app is successful. These guys have been a great team.

author
Dave Dubier
Founder & CEO, MangoMirror
coma

Mindbowser was very helpful with explaining the development process and started quickly on the project.

author
Hieu Le
Executive Director of Product Development, Innovation Lab
coma

The greatest benefit we got from Mindbowser is the expertise. Their team has developed apps in all different industries with all types of social proofs.

author
Alex Gobel
Co-Founder, Vesica
coma

Mindbowser is professional, efficient and thorough. 

author
MacKenzie R
Consultant at XPRIZE
coma

Very committed, they create beautiful apps and are very benevolent. They have brilliant Ideas.

author
Laurie Mastrogiani
Founder, S.T.A.R.S of Wellness
coma

MindBowser was great; they listened to us a lot and helped us hone in on the actual idea of the app.” “They had put together fantastic wireframes for us.

author
Bennet Gillogly
Co-Founder, Flat Earth
coma

They're very tech-savvy, yet humble.

author
Uma Nidmarty
CEO, GS Advisorate, Inc.
coma

Ayush was responsive and paired me with the best team member possible, to complete my complex vision and project. Could not be happier.

author
Katie Taylor
Founder, Child Life On Call
coma

As a founder of a budding start-up, it has been a great experience working with Mindbower Inc under Ayush's leadership for our online digital platform design and development activity.

author
Radhika Kotwal
Founder of Courtyardly
coma

The team from Mindbowser stayed on task, asked the right questions, and completed the required tasks in a timely fashion! Strong work team!

author
Michael Wright
Chief Executive Officer, SDOH2Health LLC
coma

They are focused, patient and; they are innovative. Please give them a shot if you are looking for someone to partner with, you can go along with Mindbowser.

author
David Cain
CEO, thirty2give
coma

We are a small non-profit on a budget and they were able to deliver their work at our prescribed budgets. Their team always met their objectives and I'm very happy with the end result. Thank you, Mindbowser team!!

author
Bart Mendel
Founder, Mindworks