Git Product home page Git Product logo

react-plotlyjs's Introduction

React-PlotlyJS npm version

A react component for Plotly.JS graphs.

This is a very early, simple wrapper with the following problems:

  • Performs a full redraw on every update, I intend to make this more performant soon.
  • Changes to the 'config' prop will not update the graph currently.

However it does support event handling via the onClick, onBeforeHover, onHover, onUnHover, onSelected, and onRelayout props. Note that currently, however, changes to these event handlers after initial creation will not be propogated.

As the full Plotly bundle is huge, this library lets you pass a custom bundle to create the component. Therefore you will need Plotly as a direct dependancy of your project.

import createPlotlyComponent from 'react-plotlyjs';
//See the list of possible plotly bundles at https://github.com/plotly/plotly.js/blob/master/dist/README.md#partial-bundles or roll your own
import Plotly from 'plotly.js/dist/plotly-cartesian';
const PlotlyComponent = createPlotlyComponent(Plotly);

Here's a simple example render method:

  render() {
    let data = [
      {
        type: 'scatter',  // all "scatter" attributes: https://plot.ly/javascript/reference/#scatter
        x: [1, 2, 3],     // more about "x": #scatter-x
        y: [6, 2, 3],     // #scatter-y
        marker: {         // marker is an object, valid marker keys: #scatter-marker
          color: 'rgb(16, 32, 77)' // more about "marker.color": #scatter-marker-color
        }
      },
      {
        type: 'bar',      // all "bar" chart attributes: #bar
        x: [1, 2, 3],     // more about "x": #bar-x
        y: [6, 2, 3],     // #bar-y
        name: 'bar chart example' // #bar-name
      }
    ];
    let layout = {                     // all "layout" attributes: #layout
      title: 'simple example',  // more about "layout.title": #layout-title
      xaxis: {                  // all "layout.xaxis" attributes: #layout-xaxis
        title: 'time'         // more about "layout.xaxis.title": #layout-xaxis-title
      },
      annotations: [            // all "annotation" attributes: #layout-annotations
        {
          text: 'simple annotation',    // #layout-annotations-text
          x: 0,                         // #layout-annotations-x
          xref: 'paper',                // #layout-annotations-xref
          y: 0,                         // #layout-annotations-y
          yref: 'paper'                 // #layout-annotations-yref
        }
      ]
    };
    let config = {
      showLink: false,
      displayModeBar: true
    };
    return (
      <PlotlyComponent className="whatever" data={data} layout={layout} config={config}/>
    );
  }

react-plotlyjs's People

Contributors

akloeber avatar benjeffery avatar exec64 avatar grindlemire avatar leehart avatar msiebert avatar scimonster avatar tht13 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-plotlyjs's Issues

Redraw breaks rendering

Plot redrawing is broken. The following example will show a working plot at first, but after a timer fires which triggers a new render the plot becomes broken

const Plotly = require('react-plotlyjs');

class BrokenPlot extends React.Component {
  constructor() {
    super();
    this.state = {foo: 0};
  }

  componentDidMount() {
    setTimeout(e => {
      this.setState({foo: 1});
    }, 1000);
  }

  render() {
    let layout = {
      title: 'simple example',
      xaxis: {
        title: 'time'
      }
    };
    let config = {
      showLink: false,
      displayModeBar: true
    };

    var trace1 = {
      x: [1, 2, 3, 4],
      y: [10, 15, 13, 17],
      mode: 'markers'
    };

    var trace2 = {
      x: [2, 3, 4, 5],
      y: [16, 5, 11, 9],
      mode: 'lines'
    };

    var trace3 = {
      x: [1, 2, 3, 4],
      y: [12, 9, 15, 12],
      mode: 'lines+markers'
    };

    var data = [ trace1, trace2, trace3 ];

    return (
      <Plotly className="whatever" data={data} layout={layout} config={config}/>
    );
  }
}

This wrapper library should use Plotly.newPlot instead, as described here: http://academy.plot.ly/react/3-with-plotly/

Stop performing a full redraw on every update

I saw "Performs a full redraw on every update, I intend to make this more performant soon." listed as a problem in the README, so I thought I'd add it here to make it easier to track.

Not sure if you're aware of plotly/plotly.js#204, but it looks like you project is the primary hope React+Plotly :)

Importing plotly-cartesian

How should we import the plotly-cartesian module into a Meteor app?

import Plotly from 'plotly.js/dist/plotly-cartesian';

does not work because it gives an error

Uncaught Error: Cannot find module 'plotly.js/dist/plotly-cartesian'

Is there a way to save it using something like npm install package-name --save?

Did not find these modules via npm search plotly

How to get `onPlotlyClick` event?

Plotly.js uses an onClick event for callbacks - link

How can we access this in this project?

I am able to call the function the first time, but because of the redraw, it doesn't work again.

Below is the code for a Pie Chart that uses react-motion to dynamically set rotation and pull values for user interactions:

I should note that I've also tried to use Plotly's animate module, though I don't get the smooth animation that I see from react-motion

Looking forward to hearing any suggestions you might have.

import { Motion, spring } from 'react-motion';
import React, { Component } from 'react';

import createPlotlyComponent from 'react-plotlyjs';
import formatNum from 'utils/formatCashNumbers';
import truncate from 'lodash/truncate';

export default class PieChart extends Component {
  constructor() {
    super();
    this.state = {
      rotation: 0,
      pull: 0,
    };
    this.rotation = 10;
  }
  _getData(pull, rotation) {
    let { equities, cashAvailableToTrade } = this.props;
    let data = [ ];
    equities.forEach(({ totalValue, symbol, name }) => {
      data.push({ label: truncate(name, { length: 20 }), value: totalValue });
    });
    data.push({ label: 'Cash', value: cashAvailableToTrade });
    // console.log('> Data: ', data);
    return [
      {
        values: data.map(({ value }) => value),
        labels: data.map(({ label }) => label),
        customdata: data.map(({ value }) => formatNum(value.toFixed(2))),
        type: 'pie',
        hole: 0.4,
        pull: pull,
        rotation: rotation,
        sort: true,
        opacity: 1,
        textposition: 'none',
        hoverinfo: 'label+percent+value',
        hoverlabel: {
          bordercolor: 'white',
        }
      }
    ]
  }
  _getLayout() {
    let width = 400;
    let height = 300;
    if (typeof window !== 'undefined') {
      width = window.innerWidth;
      height = 300;
    }
    if (this.props.browser.lessThan.medium) {
      height = window.innerWidth / 2;
    }
    return {
      showlegend: false,
      width: width,
      height: height,
      margin: { t: 10, r: 10, b: 10, l: 10, pad: 0 },
    };
  }
  _getConfig() {
    return {
      displayModeBar: false
    };
  }
  _clickListener() {
    document.getElementById('dashboard-pie-chart').on('plotly_click', (data) => {
      console.log('> Plotly click data: ', data, this.plotly);
      this.setState({ pull: 0.05, rotation: this.state.rotation + 10 });
    });
  }
  componentDidUpdate() {

  }
  componentDidMount() {
    this._clickListener();
  }
  render() {
    if (typeof window === 'undefined') {
      return null;
    }
    const Plotly = require('plotly.js/lib/core');

    this.plotly = Plotly;

    Plotly.register([
      require('plotly.js/lib/pie')
    ]);

    const PlotlyComponent = createPlotlyComponent(Plotly);
    return (
      <Motion style={{ pull: spring(this.state.pull), rotation: spring(this.state.rotation)}}>
        {({ pull, rotation }) => {
          return (
            <PlotlyComponent
              ref={(el) => this.chart = el}
              id="dashboard-pie-chart"
              onPlotlyClick={(data) => console.log('> Plotly click: ', data)}
              data={this._getData(pull, rotation)}
              layout={this._getLayout()}
              config={this._getConfig()}
            />
          )
        }}
      </Motion>
    )
  }
}


v0.3.6 breaks listeners

The newPlot call in componentDidUpdate introduced in v0.3.6 removes the old event listeners whenever componentDidUpdate is called. It may be that Plotly does some amount of mangling to the container which removes the listeners.

In the short term it can be fixed by reapplying all the listeners every update but I am unsure of how it should be done in the long term

Can't change plot div className

I am trying to style my graph with a loading animation when there is no data in my component's props yet.

Here is a gist with what my code looks like: https://gist.github.com/zachschultz/b3e7261cd774d0c54b21c2100381c6fb

UPDATE: Adding a console.log statement into the div makes this magically work...still have no idea why.

Essentially, if the graph data doesn't exist, I want to show a Plotly graph that will be grayed out with a spinning loading logo on it. However, this isn't working, and when my graph data comes in the graph itself doesn't re-render with data, it just stays blank.

I know for a fact the data is there and that the graph data state is being updated as well, so I'm really not sure what is going wrong here.

Can't update the data in my plot

Hello,

I was able to get the polar scatter plot working, but I cannot figure out how to add new data to the plot without trouble. When I use setState it causes the plot to slap a new empty plot, not even the same type over top of the old plot. The old plot remains unchanged and underneath the new empty plot...

Let me know if you are able to update the plot's data and if so, could you post the code for doing it correctly? I could really use a polar scatter plot in my project :)

PlotlyComponent.js:5:1: Unexpected token (5:1)

Hi, I just tried read me example using meteor with react, then server shows this error, even when I delete all code and just only install the package:
While processing files with ecmascript (for target web.browser):
packages/nicodinh:meteor-react-plotlyjs/PlotlyComponent.js:5:1: Unexpected token (5:1)

While processing files with ecmascript (for target os.windows.x86_64):
packages/nicodinh:meteor-react-plotlyjs/PlotlyComponent.js:5:1: Unexpected token (5:1)

Event props raise error on start

Using OnHover \ onUnHover for example works, but raises an error for using unknown props on 'div'.
Solution: just remove the '...others' from the div. You don't need them there.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.