Convert Figma logo to code with AI

plotly logoreact-plotly.js

A plotly.js React component from Plotly 📈

1,013
136
1,013
144

Top Related Projects

16,856

Open-source JavaScript charting library behind Plotly and Dash

23,653

Redefined chart library built with React and D3

10,956

A collection of composable React components for building interactive data visualizations

📊 Interactive JavaScript Charts built on SVG

13,066

nivo provides a rich set of dataviz components, built on top of the awesome d3 and React libraries

64,334

Simple HTML5 Charts using the <canvas> tag

Quick Overview

React-Plotly.js is a React component for creating interactive, publication-quality graphs and charts using Plotly.js. It provides a declarative way to create Plotly charts within React applications, making it easier to integrate data visualization into React-based projects.

Pros

  • Seamless integration with React applications
  • Supports a wide range of chart types and customization options
  • Provides interactive features like zooming, panning, and hover tooltips out of the box
  • Offers good performance for large datasets

Cons

  • Large bundle size due to the inclusion of the full Plotly.js library
  • Learning curve can be steep for complex visualizations
  • Limited server-side rendering support
  • Documentation could be more comprehensive for advanced use cases

Code Examples

  1. Creating a basic line chart:
import React from 'react';
import Plot from 'react-plotly.js';

const LineChart = () => (
  <Plot
    data={[
      {
        x: [1, 2, 3, 4],
        y: [10, 15, 13, 17],
        type: 'scatter',
        mode: 'lines+markers',
        marker: {color: 'red'},
      },
    ]}
    layout={{width: 720, height: 480, title: 'A Simple Line Chart'}}
  />
);
  1. Creating a bar chart with multiple traces:
import React from 'react';
import Plot from 'react-plotly.js';

const BarChart = () => (
  <Plot
    data={[
      {x: ['A', 'B', 'C'], y: [20, 14, 23], type: 'bar', name: 'Series 1'},
      {x: ['A', 'B', 'C'], y: [12, 18, 29], type: 'bar', name: 'Series 2'},
    ]}
    layout={{width: 720, height: 480, title: 'Bar Chart with Multiple Series'}}
  />
);
  1. Creating a responsive plot:
import React from 'react';
import Plot from 'react-plotly.js';

const ResponsivePlot = () => (
  <Plot
    data={[
      {x: [1, 2, 3], y: [2, 6, 3], type: 'scatter', mode: 'lines+markers'},
    ]}
    layout={{
      title: 'Responsive Plot',
      autosize: true,
    }}
    useResizeHandler={true}
    style={{width: '100%', height: '100%'}}
  />
);

Getting Started

To use react-plotly.js in your React project:

  1. Install the package:

    npm install react-plotly.js plotly.js
    
  2. Import and use the component in your React code:

    import React from 'react';
    import Plot from 'react-plotly.js';
    
    function App() {
      return (
        <Plot
          data={[
            {x: [1, 2, 3], y: [2, 6, 3], type: 'scatter', mode: 'lines+markers'},
          ]}
          layout={{width: 720, height: 480, title: 'My First Plot'}}
        />
      );
    }
    
    export default App;
    

This will create a basic line chart in your React application. You can customize the data and layout props to create different types of charts and adjust their appearance.

Competitor Comparisons

16,856

Open-source JavaScript charting library behind Plotly and Dash

Pros of plotly.js

  • More flexible and can be used with various frameworks or vanilla JavaScript
  • Offers a wider range of chart types and customization options
  • Smaller bundle size when only specific chart types are needed

Cons of plotly.js

  • Requires more setup and configuration for React projects
  • Less integrated with React's component-based architecture
  • May require additional wrapper components for optimal React usage

Code Comparison

plotly.js:

var data = [{x: [1, 2, 3], y: [2, 4, 8]}];
var layout = {title: 'Simple Plot'};
Plotly.newPlot('myDiv', data, layout);

react-plotly.js:

import Plot from 'react-plotly.js';

function MyPlot() {
  return (
    <Plot data={[{x: [1, 2, 3], y: [2, 4, 8]}]} layout={{title: 'Simple Plot'}} />
  );
}

The plotly.js example shows direct DOM manipulation, while react-plotly.js integrates seamlessly with React components. react-plotly.js simplifies the process of creating Plotly charts in React applications, offering a more declarative approach. However, plotly.js provides more flexibility for use in various environments and can be more efficient when only specific chart types are needed.

23,653

Redefined chart library built with React and D3

Pros of Recharts

  • Lightweight and optimized for performance
  • Built specifically for React, offering seamless integration
  • Highly customizable with a declarative API

Cons of Recharts

  • Limited chart types compared to React-Plotly.js
  • Less extensive documentation and community support
  • May require more custom coding for complex visualizations

Code Comparison

Recharts:

import { LineChart, Line, XAxis, YAxis } from 'recharts';

<LineChart width={400} height={300} data={data}>
  <Line type="monotone" dataKey="value" stroke="#8884d8" />
  <XAxis dataKey="name" />
  <YAxis />
</LineChart>

React-Plotly.js:

import Plot from 'react-plotly.js';

<Plot
  data={[{x: [1, 2, 3], y: [2, 6, 3], type: 'scatter', mode: 'lines+markers'}]}
  layout={{width: 400, height: 300, title: 'Line Chart'}}
/>

Both libraries offer React-friendly APIs for creating charts, but Recharts provides a more React-specific approach with individual components for chart elements. React-Plotly.js, on the other hand, uses a single Plot component with configuration objects, leveraging the power of Plotly.js.

10,956

A collection of composable React components for building interactive data visualizations

Pros of Victory

  • Lightweight and modular, allowing for smaller bundle sizes
  • Fully customizable with a more React-centric API
  • Better performance for large datasets and real-time updates

Cons of Victory

  • Less extensive chart types compared to react-plotly.js
  • Steeper learning curve for complex visualizations
  • Limited built-in interactivity features

Code Comparison

Victory:

import { VictoryBar, VictoryChart, VictoryAxis } from 'victory';

<VictoryChart>
  <VictoryBar data={data} x="quarter" y="earnings" />
  <VictoryAxis tickValues={[1, 2, 3, 4]} tickFormat={["Q1", "Q2", "Q3", "Q4"]} />
</VictoryChart>

react-plotly.js:

import Plot from 'react-plotly.js';

<Plot
  data={[{ type: 'bar', x: [1, 2, 3, 4], y: data.map(d => d.earnings) }]}
  layout={{ xaxis: { tickvals: [1, 2, 3, 4], ticktext: ["Q1", "Q2", "Q3", "Q4"] } }}
/>

Victory offers a more declarative, component-based approach, while react-plotly.js provides a more configuration-driven API. Victory's modular structure allows for fine-grained control over chart elements, whereas react-plotly.js leverages Plotly's extensive charting capabilities with a simpler setup.

📊 Interactive JavaScript Charts built on SVG

Pros of ApexCharts.js

  • Lightweight and fast rendering, especially for large datasets
  • Extensive customization options and interactive features
  • Better mobile responsiveness and touch support

Cons of ApexCharts.js

  • Less comprehensive documentation compared to React-Plotly.js
  • Fewer chart types available, especially for scientific and statistical visualizations
  • Limited 3D chart capabilities

Code Comparison

ApexCharts.js:

import ApexCharts from 'apexcharts'

const options = {
  chart: { type: 'line' },
  series: [{ data: [30, 40, 35, 50, 49, 60, 70] }],
  xaxis: { categories: [1991, 1992, 1993, 1994, 1995, 1996, 1997] }
}

const chart = new ApexCharts(document.querySelector("#chart"), options)
chart.render()

React-Plotly.js:

import Plot from 'react-plotly.js'

const MyPlot = () => (
  <Plot
    data={[{ x: [1991, 1992, 1993, 1994, 1995, 1996, 1997], y: [30, 40, 35, 50, 49, 60, 70], type: 'scatter' }]}
    layout={{ width: 720, height: 480, title: 'A Line Plot' }}
  />
)
13,066

nivo provides a rich set of dataviz components, built on top of the awesome d3 and React libraries

Pros of nivo

  • Built specifically for React, offering better integration and performance
  • Provides a wide range of customizable chart types out-of-the-box
  • Supports server-side rendering for improved SEO and initial load times

Cons of nivo

  • Smaller community and less extensive documentation compared to react-plotly.js
  • Limited interactivity options compared to the rich interactive features of Plotly
  • Steeper learning curve for developers new to D3.js concepts

Code Comparison

nivo:

import { ResponsiveLine } from '@nivo/line'

<ResponsiveLine
    data={data}
    margin={{ top: 50, right: 110, bottom: 50, left: 60 }}
    xScale={{ type: 'point' }}
    yScale={{ type: 'linear', min: 'auto', max: 'auto', stacked: true, reverse: false }}
/>

react-plotly.js:

import Plot from 'react-plotly.js'

<Plot
    data={[
        { x: [1, 2, 3], y: [2, 6, 3], type: 'scatter', mode: 'lines+markers', marker: {color: 'red'} },
    ]}
    layout={{ width: 320, height: 240, title: 'A Fancy Plot' }}
/>
64,334

Simple HTML5 Charts using the <canvas> tag

Pros of Chart.js

  • Lightweight and fast, with a smaller file size
  • Simple and easy to use, especially for basic charts
  • Extensive documentation and community support

Cons of Chart.js

  • Limited customization options compared to React-Plotly.js
  • Fewer chart types and advanced features
  • Less suitable for complex, interactive data visualizations

Code Comparison

Chart.js:

import Chart from 'chart.js/auto';

new Chart(ctx, {
    type: 'bar',
    data: chartData,
    options: chartOptions
});

React-Plotly.js:

import Plot from 'react-plotly.js';

<Plot
    data={[{x: [1, 2, 3], y: [2, 6, 3], type: 'scatter'}]}
    layout={{width: 320, height: 240, title: 'A Fancy Plot'}}
/>

Chart.js is more straightforward for simple charts, while React-Plotly.js offers more flexibility and options for complex visualizations. Chart.js is ideal for projects requiring basic charts with minimal setup, whereas React-Plotly.js is better suited for data-intensive applications needing advanced interactivity and customization.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

react-plotly.js

plotly-react-logo

A plotly.js React component from Plotly. The basis of Plotly's React component suite.

👉 DEMO

👉 Demo source code


Contents

Installation

$ npm install react-plotly.js plotly.js

Quick start

The easiest way to use this component is to import and pass data to a plot component:

import React from 'react';
import Plot from 'react-plotly.js';

class App 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: 'A Fancy Plot'}}
      />
    );
  }
}

You should see a plot like this:

Example plot

For a full description of Plotly chart types and attributes see the following resources:

State management

This is a "dumb" component that doesn't merge its internal state with any updates. This means that if a user interacts with the plot, by zooming or panning for example, any subsequent re-renders will lose this information unless it is captured and upstreamed via the onUpdate callback prop.

Here is a simple example of how to capture and store state in a parent object:

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {data: [], layout: {}, frames: [], config: {}};
  }

  render() {
    return (
      <Plot
        data={this.state.data}
        layout={this.state.layout}
        frames={this.state.frames}
        config={this.state.config}
        onInitialized={(figure) => this.setState(figure)}
        onUpdate={(figure) => this.setState(figure)}
      />
    );
  }
}

Refreshing the Plot

This component will refresh the plot via Plotly.react if any of the following are true:

  • The revision prop is defined and has changed, OR;
  • One of data, layout or config has changed identity as checked via a shallow ===, OR;
  • The number of elements in frames has changed

Furthermore, when called, Plotly.react will only refresh the data being plotted if the identity of the data arrays (e.g. x, y, marker.color etc) has changed, or if layout.datarevision has changed.

In short, this means that simply adding data points to a trace in data or changing a value in layout will not cause a plot to update unless this is done immutably via something like immutability-helper if performance considerations permit it, or unless revision and/or layout.datarevision are used to force a rerender.

API Reference

Basic Props

Warning: for the time being, this component may mutate its layout and data props in response to user input, going against React rules. This behaviour will change in the near future once https://github.com/plotly/plotly.js/issues/2389 is completed.

PropTypeDefaultDescription
dataArray[]list of trace objects (see https://plot.ly/javascript/reference/)
layoutObjectundefinedlayout object (see https://plot.ly/javascript/reference/#layout)
framesArrayundefinedlist of frame objects (see https://plot.ly/javascript/reference/)
configObjectundefinedconfig object (see https://plot.ly/javascript/configuration-options/)
revisionNumberundefinedWhen provided, causes the plot to update when the revision is incremented.
onInitializedFunction(figure, graphDiv)undefinedCallback executed after plot is initialized. See below for parameter information.
onUpdateFunction(figure, graphDiv)undefinedCallback executed when a plot is updated due to new data or layout, or when user interacts with a plot. See below for parameter information.
onPurgeFunction(figure, graphDiv)undefinedCallback executed when component unmounts, before Plotly.purge strips the graphDiv of all private attributes. See below for parameter information.
onErrorFunction(err)undefinedCallback executed when a plotly.js API method rejects
divIdstringundefinedid assigned to the <div> into which the plot is rendered.
classNamestringundefinedapplied to the <div> into which the plot is rendered
styleObject{position: 'relative', display: 'inline-block'}used to style the <div> into which the plot is rendered
debugBooleanfalseAssign the graph div to window.gd for debugging
useResizeHandlerBooleanfalseWhen true, adds a call to Plotly.Plot.resize() as a window.resize event handler

Note: To make a plot responsive, i.e. to fill its containing element and resize when the window is resized, use style or className to set the dimensions of the element (i.e. using width: 100%; height: 100% or some similar values) and set useResizeHandler to true while setting layout.autosize to true and leaving layout.height and layout.width undefined. This can be seen in action in this CodePen and will implement the behaviour documented here: https://plot.ly/javascript/responsive-fluid-layout/

Callback signature: Function(figure, graphDiv)

The onInitialized, onUpdate and onPurge props are all functions which will be called with two arguments: figure and graphDiv.

  • figure is a serializable object with three keys corresponding to input props: data, layout and frames.
    • As mentioned above, for the time being, this component may mutate its layout and data props in response to user input, going against React rules. This behaviour will change in the near future once https://github.com/plotly/plotly.js/issues/2389 is completed.
  • graphDiv is a reference to the (unserializable) DOM node into which the figure was rendered.

Event handler props

Event handlers for specific plotly.js events may be attached through the following props:

PropTypePlotly Event
onAfterExportFunctionplotly_afterexport
onAfterPlotFunctionplotly_afterplot
onAnimatedFunctionplotly_animated
onAnimatingFrameFunctionplotly_animatingframe
onAnimationInterruptedFunctionplotly_animationinterrupted
onAutoSizeFunctionplotly_autosize
onBeforeExportFunctionplotly_beforeexport
onBeforeHoverFunctionplotly_beforehover
onButtonClickedFunctionplotly_buttonclicked
onClickFunctionplotly_click
onClickAnnotationFunctionplotly_clickannotation
onDeselectFunctionplotly_deselect
onDoubleClickFunctionplotly_doubleclick
onFrameworkFunctionplotly_framework
onHoverFunctionplotly_hover
onLegendClickFunctionplotly_legendclick
onLegendDoubleClickFunctionplotly_legenddoubleclick
onRelayoutFunctionplotly_relayout
onRelayoutingFunctionplotly_relayouting
onRestyleFunctionplotly_restyle
onRedrawFunctionplotly_redraw
onSelectedFunctionplotly_selected
onSelectingFunctionplotly_selecting
onSliderChangeFunctionplotly_sliderchange
onSliderEndFunctionplotly_sliderend
onSliderStartFunctionplotly_sliderstart
onSunburstClickFunctionplotly_sunburstclick
onTransitioningFunctionplotly_transitioning
onTransitionInterruptedFunctionplotly_transitioninterrupted
onUnhoverFunctionplotly_unhover
onWebGlContextLostFunctionplotly_webglcontextlost

Customizing the plotly.js bundle

By default, the Plot component exported by this library loads a precompiled version of all of plotly.js, so plotly.js must be installed as a peer dependency. This bundle is around 6Mb unminified, and minifies to just over 2Mb.

If you do not wish to use this version of plotly.js, e.g. if you want to use a different precompiled bundle or if your wish to assemble you own customized bundle, or if you wish to load plotly.js from a CDN, you can skip the installation of as a peer dependency (and ignore the resulting warning) and use the createPlotComponent method to get a Plot component, instead of importing it:

// simplest method: uses precompiled complete bundle from `plotly.js`
import Plot from 'react-plotly.js';

// customizable method: use your own `Plotly` object
import createPlotlyComponent from 'react-plotly.js/factory';
const Plot = createPlotlyComponent(Plotly);

Loading from a <script> tag

For quick one-off demos on CodePen or JSFiddle, you may wish to just load the component directly as a script tag. We don't host the bundle directly, so you should never rely on this to work forever or in production, but you can use a third-party service to load the factory version of the component from, for example, https://unpkg.com/react-plotly.js@latest/dist/create-plotly-component.js.

You can load plotly.js and the component factory with:

<script src="https://cdn.plot.ly/plotly-latest.min.js"></script>
<script src="https://unpkg.com/react-plotly.js@latest/dist/create-plotly-component.js"></script>

And instantiate the component with

const Plot = createPlotlyComponent(Plotly);

ReactDOM.render(
  React.createElement(Plot, {
    data: [{x: [1, 2, 3], y: [2, 1, 3]}],
  }),
  document.getElementById('root')
);

You can see an example of this method in action here.

Development

To get started:

$ npm install

To transpile from ES2015 + JSX into the ES5 npm-distributed version:

$ npm run prepublishOnly

To run the tests:

$ npm run test

License

© 2017-2020 Plotly, Inc. MIT License.

NPM DownloadsLast 30 Days