Git Product home page Git Product logo

react-plotly.js's People

Contributors

alexcjohnson avatar andrefarzat avatar antoinedoubovetzky avatar antoinerg avatar bpostlethwaite avatar dmt0 avatar etpinard avatar jackparmer avatar keonik avatar lauri-codes avatar markovist avatar mikerippon avatar nicolaskruchten avatar rreusser avatar verazab avatar zoryamba 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  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

react-plotly.js's Issues

stop using componentWillUpdate

Currently we update the plot in componentWillUpdate - it works, but it's a little weird and this method is deprecated.

  • Put the conditionals preventing updates into shouldComponentUpdate?
  • Move the update itself to componentDidUpdate
  • The chain of events in componentDidMount (initial draw) and the update code are a little different, but there may be some opportunity to DRY this up - at least, the Plotly.newPlot in the initial draw can safely be turned into Plotly.react.

react-plotly does not work with webpack

in my package.json

  "dependencies": {
    "ify-loader": "^1.1.0",
    "mobx": "^3.0.0",
    "mobx-react": "^4.1.0",
    "mobx-react-devtools": "^4.2.11",
    "plotly.js": "^1.31.2",
    "react": "^15.1.0",
    "react-dom": "^15.1.0",
    "react-plotly.js": "^1.0.4"
  },
  "browserify": { 
    "transform": [ "plotly" ] 
  }

in my webpack.conf

  node: {
    fs: "empty"
  },
  module: {
    rules: [{
      test: /\.jsx?$/,
      use: ['babel-loader'],
      include: path.join(__dirname, 'src')
    }],
    loaders: [{
      test: /node_modules.*\.js$/,
      loader: 'ify-loader'
    }]
  }

it still gives my an error like this:
browser.js:2 Uncaught Error: It appears that you're using glslify in browserify without its transform applied. Make sure that you've set up glslify as a source transform

Expose Plotly.restyle

Exposing restyle allows for updating styles on the chart without having to update all of the data.

ie. change the color or size of a marker when clicked.

Error: It appears that you're using glslify in browserify without its transform applied.

If the React project is created with create-react-app, this error is thrown:

Importing react-plotly.js throws "browser.js:2
Uncaught Error: It appears that you're using glslify in browserify without its transform applied. Make sure that you've set up glslify as a source transform" with React app created using create-react-app

It appears that this is caused by using Webpack, which create-react-app uses internally. Unfortunately, create-react-app doesn't expose the webpack.config.js/webpack.config.json files to apply the workaround in the README of https://github.com/plotly/plotly.js. I am using the workaround copied from jupyterlab/jupyter-renderers#10:

import Plotly from 'plotly.js/lib/core';
import plotComponentFactory from 'react-plotly.js/factory';
const Plot = plotComponentFactory(Plotly);

But I would like to know if there's a better way. Thanks!

"Selected data" with Parallel Coordinates Chart

Hi,

I found in another thread, there's an example of using "onRestyle" event to get "constraintrange" data. However, this is not the data of highlighted lines of parcoords chart. is there a simpler way to find "highlighted" line data from the event handler?

Thank you!

How used TouchEvent

Hello,
I use this lib for a company project. Honestly, i like react-plotly/plotly but i'm blocking on a important problem:
My react app is responsive and a lot of customers use it on tablet or mobile.

I don't know if I forgot somethings but i can't understand what I have to do for use TouchEvent.
screengraph
screenerrortouchevent.

I have all the time this warning.
How should I do it with react-plotly ?

Thank you in advance

fit property doc is wrong?

The fit property documentation appears to be wrong in that any existing layout.width or layout.height is not ignored... Need to decide if the docs should be updated to match the implementation or vice versa.

Failed to minify on production build

Ok, so I created a new react app with create-react-app, added react-plotly.js to my project/code, ran into the "using glsify without its transform applied" problem (issue #13), and after reading through the various solutions, opted to do a npm run eject so I could add ify-loader to my webpack.config.dev.js and webpack.config.prod.js (ala https://github.com/plotly/plotly.js#building-plotlyjs-with-webpack).

This fixed the problem in dev mode, and I can get my component to display just fine when running the dev server (npm start). However, now if I try to do a 'npm run build' to build a production version, I get the following error:

Failed to compile.

Failed to minify the code from this file: 

 	./node_modules/ify-loader!./node_modules/gl-matrix/src/gl-matrix/common.js:28 

Read more here: http://bit.ly/2tRViJ9

I've looked around, but I can't seem to find much of a hint on how to fix this.. any ideas?

How to use the layout.autosize?

Good day, I'm having problem with the attribute autosize of layout property, I set to true but is not working as the docs says:

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 will implement the behaviour documented here: https://plot.ly/javascript/responsive-fluid-layout/

What I want is have a container that defines the area of the charts like I highlighted in this image:
react-ploty-autoresize

fs.readFileSync not a function

Getting this error while importing react-plotly.js -import Plot from 'react-plotly.js'.

index.js:7 Uncaught TypeError: fs.readFileSync is not a function
    at Object.<anonymous> (index.js:7)
    at Object.splitPathRe (index.js:60)
    at __webpack_require__ (bootstrap 58ec34c915a8f5342f30:19)
    at Object.<anonymous> (use_program.js:5)
    at __webpack_require__ (bootstrap 58ec34c915a8f5342f30:19)
    at Object.defineProperty.value (painter.js:43)
    at __webpack_require__ (bootstrap 58ec34c915a8f5342f30:19)
    at Object.<anonymous> (map.js:12)
    at __webpack_require__ (bootstrap 58ec34c915a8f5342f30:19)
    at Object.module.exports (mapbox-gl.js:8)

Node - 9.5.0
react 16.2.0
webpack 3.10
react-plotly 1.5.0

Resize handler not removed when fit property is true

When a Plotly-React plot is removed from page (props.fit is true) the following error occurs when resizing the window:

Uncaught TypeError: Cannot read property 'parentElement' of null
    at PlotlyComponent.getParentSize (factory.js:251)
    at PlotlyComponent.getSize (factory.js:264)
    at resizeHandler (factory.js:195)
getParentSize @ factory.js:251
getSize @ factory.js:264
resizeHandler @ factory.js:195

React + mobx -> chart is not updating.

Sorry to bother again, but I can not update my chart via data polling. While I can see the text properties updating the chart does not move. However if I feed the data a priori the chart renders nicely. Is this a problem with the Plot component or is this related to mobx, or did I stimple make a mistake?

import React, { Component } from "react";
import { observer } from "mobx-react";
import Plot from 'react-plotly.js';

@observer
class DemoPlot extends React.Component {
    componentDidMount() {
        this.props.store.poll();
    }

    render() {
        return(
            <div>
                {this.props.store.error} / {this.props.store.nextOffset} / {this.props.store.x.length} / {this.props.store.y.length}
            <Plot data={[
                    {
                    type: 'scatter',
                    mode: 'lines+points',
                    x: this.props.store.x,
                    y: this.props.store.y,
                    marker: {color: 'red'}
                    }
                ]}

                layout={{
                    width: 1000,
                    height: 240,
                    title: 'A Fancy Plot'
                }}
                />
                </div>
        );
    }
}

export default DemoPlot;

PS would you eventually consider to create and maintain a tag on stackoverflow?

Accessing pixel coordinates of data without event

I'm trying to do something similar to the following forums where I'm trying to get the x, y coordinates of a data point in order to use the Fx.loneHover to programmatically trigger a hover event.

Any advice on how to achieve this? If I inspect the chart ref in the PlotlyComponent in does not have the function l2p or d2p anywhere within the object and I do not have an event handle to use to retrieve the x and y relative pixel locations.

Props should not be mutated by Plot component

It seems like the Plot component mutates its props (at least layout) instead of cloning the data.
Mutation of props is to me unexpected (and undesired) behavior for a react component.

If for instance the layout is stored in the state of a component and then fed to the Plot component as a prop, like

render() {
  <Plot
    layout={this.state.layout},
    ...
    />

we will have a problem, since this.state only should be updated with the react setState() method.

Tons of `npm WARN deprecated`

$ npm install react-plotly.js plotly.js

npm WARN deprecated [email protected]: Project renamed to HSLuv
npm WARN deprecated [email protected]: This package has been merged into the 'mapbox-gl-style-spec' package
npm WARN deprecated [email protected]: This package has been merged with the 'mapbox-gl-style-spec' package
npm WARN deprecated [email protected]: This module has moved: please install @mapbox/point-geometry instead
npm WARN deprecated [email protected]: This package has been moved to @mapbox/mapbox-gl-supported
npm WARN deprecated [email protected]: This module is now under the @mapbox namespace: install @mapbox/shelf-pack instead
npm WARN deprecated [email protected]: This module has moved: switch to @mapbox/unitbezier
npm WARN deprecated [email protected]: This module has moved: please install @mapbox/vector-tile instead
npm WARN deprecated [email protected]: This module is now under the @mapbox namespace: install @mapbox/whoots-js instead

Can't resolve 'vertx' in '~/node_modules/plotly.js/dist'

I get the above warning in development, although plotly appears to work just fine.

  • Webpack 4.5.1
  • React 16.3.1
  • Plotly.js 1.35.1
  • React-plotly.js 2.1.0

There seems to be a lot of mixed opinions on how to get react-plotly working in a webpack setup, in my case I'm not using ify-loader

Here's my js webpack rules if it helps

module: {
    // Make missing exports an error instead of warning
    strictExportPresence: true,

    rules: [
      // Rules for JS / JSX
      {
        test: reScript,
        include: [SRC_DIR, resolvePath('tools')],
        loader: 'babel-loader',
        options: {
          // https://github.com/babel/babel-loader#options
          cacheDirectory: isDebug,

          // https://babeljs.io/docs/usage/options/
          babelrc: false,
          presets: [
            // A Babel preset that can automatically determine the Babel plugins and polyfills
            // https://github.com/babel/babel-preset-env
            [
              '@babel/preset-env',
              {
                targets: {
                  browsers: pkg.browserslist,
                  forceAllTransforms: !isDebug, // for UglifyJS
                },
                modules: false,
                useBuiltIns: false,
                debug: false,
              },
            ],
            // Experimental ECMAScript proposals
            // https://babeljs.io/docs/plugins/#presets-stage-x-experimental-presets-
            '@babel/preset-stage-2',
            // Flow
            // https://github.com/babel/babel/tree/master/packages/babel-preset-flow
            '@babel/preset-flow',
            // JSX
            // https://github.com/babel/babel/tree/master/packages/babel-preset-react
            ['@babel/preset-react', { development: isDebug }],
          ],
          plugins: [
            // Treat React JSX elements as value types and hoist them to the highest scope
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-constant-elements
            ...(isDebug ? [] : ['@babel/transform-react-constant-elements']),
            // Replaces the React.createElement function with one that is more optimized for production
            // https://github.com/babel/babel/tree/master/packages/babel-plugin-transform-react-inline-elements
            ...(isDebug ? [] : ['@babel/transform-react-inline-elements']),
            // Remove unnecessary React propTypes from the production build
            // https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types
            ...(isDebug ? [] : ['transform-react-remove-prop-types']),
          ],
        },
      },

Edit:
I just realized that I can't build production if I'm using UglifyJS, the build process just goes on forever. If I comment out uglifyjs the build completes in a few minutes and runs fine. Any ideas here?

// Move modules that occur in multiple entry chunks to a new entry chunk (the commons chunk).
  optimization: {
    minimizer: [
       new UglifyJsPlugin({
         cache: true,
         parallel: true,
         sourceMap: false // set to true if you want JS source maps
       }),
       new OptimizeCSSAssetsPlugin({})
    ],
    splitChunks: {
      cacheGroups: {
        styles: {
          name: 'styles',
          test: /\.s?css$/,
          chunks: 'all',
          enforce: true,
        },
        commons: {
          chunks: 'initial',
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
        },
      },
    },
  },

Plot Properties in Data Objects Not Affecting Output

I have an array of shape objects. The boundaries are plotting fine, however, the properties in the data objects are not affecting the plot, For example I would like to fill the shapes. I appreciate any ideas you may have.
Thank you!
The Output:
image

The Code:
image

react-plotly.js not working with node in SSR context

[email protected] start /home/username/project
node ./lib/server/app.js

/home/username/project/node_modules/plotly.js/src/lib/is_plain_object.js:19
if(window && window.process && window.process.versions) {
^

ReferenceError: window is not defined
at isPlainObject (/home/mastcoder/metabrainz/bookbrainz-site/node_modules/plotly.js/src/lib/is_plain_object.js:19:5)
at overrideAll (/home/mastcoder/metabrainz/bookbrainz-site/node_modules/plotly.js/src/plot_api/edit_types.js:123:12)
at Object. (/home/mastcoder/metabrainz/bookbrainz-site/node_modules/plotly.js/src/components/colorbar/attributes.js:17:18)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (module.js:560:32)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
at Module.require (module.js:585:17)
at require (internal/module.js:11:18)
at Object. (/home/username/project/node_modules/plotly.js/src/traces/scatter/attributes.js:13:21)
at Module._compile (module.js:641:30)
at Object.Module._extensions..js (module.js:652:10)
at Module.load (module.js:560:32)
at tryModuleLoad (module.js:503:12)
at Function.Module._load (module.js:495:3)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: node ./lib/server/app.js
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! /home/username/.npm/_logs/2018-02-14T10_21_38_925Z-debug.log

React plotly components website currently giving certificate error

https://react.plot.ly/ is currently not loading in chrome. I got this at work and at home on completely different setups:

react.plot.ly normally uses encryption to protect your information. When Google Chrome tried to connect to react.plot.ly this time, the website sent back unusual and incorrect credentials. This may happen when an attacker is trying to pretend to be react.plot.ly, or a Wi-Fi sign-in screen has interrupted the connection. Your information is still secure because Google Chrome stopped the connection before any data was exchanged.

You cannot visit react.plot.ly right now because the website uses HSTS. Network errors and attacks are usually temporary, so this page will probably work later.

Plotly.react

Seeking feedback from @etpinard @alexcjohnson @bpostlethwaite on the best location for Plotly.react. I can imagine a few possibilities:

  1. it should go in plotly.js and we just have to add a couple lines of code to this repo to make use of it.
  • Pro: react-like functionality usable from any library
  • Con: more code in plotly.js
  1. it goes in this repo. It computes a diff (maybe using the schema to figure out what to do about array data, with optional flag to apply immutable-like reference-change logic to simplify diff computation) and sends the result to the relevant plotly.js API methods.
  • Pro/con: opposites of above

Unless I'm wrong, sounds like @alexcjohnson is/will be working on Plotly.react. I just wanted to confirm that's what this will link up with.

testing with create-react-app

Hi! Thanks for all the good work.

I am trying to make the simple test that comes with create-react-app to work. (Which checks whole app renders without a crash)

I get an error like below.

    TypeError: Cannot read property 'document' of undefined
      
      at node_modules/plotly.js/dist/plotly.js:74:22
      at node_modules/plotly.js/dist/plotly.js:9620:2
      at Object.<anonymous>._$numerical_517.BADNUM (node_modules/plotly.js/dist/plotly.js:7:88)
      at Object.<anonymous> (node_modules/plotly.js/dist/plotly.js:7:327)
      at Object.<anonymous> (node_modules/react-plotly.js/react-plotly.js:11:15)
      at Object.<anonymous> (src/components/Graph/StyledGraph.js:2:20)
      at Object.<anonymous> (src/components/Graph/index.js:4:20)
      at Object.<anonymous> (src/container/GraphContainer.js:6:14)
      at Object.<anonymous> (src/App.js:7:23)
      at Object.<anonymous> (src/Main.js:14:12)
      at Object.<anonymous> (src/App.test.js:5:13)

I am using pretty much the default command that comes with create-react-app. (Test command node scripts/test.js --env=jsdom, react-app-preset)
import Plotly from 'plotly.js/dist/basic';

I am using Plotly like below.

import Plotly from 'plotly.js/dist/basic';
import createPlotlyComponent from 'react-plotly.js/factory';
const Plot = createPlotlyComponent(Plotly);

Graph not changing on input change

According to the docs: This component currently creates a new plot every time the input changes.
It seems like the graph would do a redraw once the data changed. When passing updated props to the <Plot/> data attribute the plot stays the same.

Even when checking in componentWillReceiveProps() the nextProps.data is different than the this.props.data.

Update:
The same seems true when incrementing the revision attribute.

EventEmitter memory leak

I get the following error in console:

(node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit.

Not sure what causes it, but it seems to be related to dynamic data updates. It can be seen in this example: CodePen. Click "Add data" and watch console.

SSR

doesn't appear that this library supports server-side rendering, which is a must for using frameworks like Next.js

Any plans to support this? I wanted to port over from another implementation but will have to wait :/

Performance Issues

I am currently working on a visualization tool that has multiple animations going on at the same time. What I am trying to do is look at how a graph evolves over time, so I have the graph I am watching evolve in one pane (using GoldenLayout) and a timline graph in a another pane with an aggregation shown on it. What I am trying to do is display a black line on the timeline graph and animate it while I am animating the change in the main graph, but unfortunately this is resulting in very poor performance (whole screen stops after a while or starts flickering depending on what I've tried and the black line is never show).

My application is using Redux and that is how I start / stop / run animations. In the animation component I use the following interval to animate the graphs:

animate = (timestamp) => {
    if (this.lastTime === null) {
      this.lastTime = timestamp;
    }
    this.props.addAnimationMsTime(timestamp - this.lastTime);
    this.lastTime = timestamp;
    if (this.props.animation.get('animating')) {
      window.requestAnimationFrame(this.animate.bind(this));
    }
  };

(I know it's not the best practice to put this here, so if you have any other ideas on where it should go, that would be greatly appreciated.)

From here the data goes to the main graph and updates the entire graph. My data is parsed on a web-worker ahead of time and pre-imported into the component at construction time. Since I wanted web-worker transfer times and data-switching to be quick, I put my data into Uint32Arrays, since they are transferable over web-workers and switching to a different portion of data is just constructing a data-view on the buffer, which at least as fast as array.slice(). There are separate arrays for the x and y axes. Component data is updated when the current time slice being viewed changes (which changes with previous interval). Since my data doesn't have a datapoint for every instant, I have to do a binary search to find the closest point. Then, on another frame interval, the data is updated on the main graph:

updateChart() {
    if (this.hasUpdatedSinceLast) {
      this.hasUpdatedSinceLast = false;
      const backtracksPerLevelIndex = closestBinarySearch(
        this.props.backtracksPerLevelTime,
        this.props.currentTime,
        (time) => time,
      );

      this.currentBacktracksPerLevel = new Uint32Array(
        this.props.backtracksPerLevel.buffer,
        4 * (this.props.numVars + 1) * backtracksPerLevelIndex,
        this.props.numVars + 1
      );

      const algoFiresIndex = closestBinarySearch(
        this.props.algoFiresTime,
        this.props.currentTime,
        (time) => time,
      );

      this.currentAlgoFires = [];
      for (let i = 0; i < this.props.algoOrder.length; i++) {
        this.currentAlgoFires[i] = new Uint32Array(
          this.props.algoFires.buffer,
          4 * ((this.props.numVars + 1) * this.props.algoOrder.length * algoFiresIndex +
            (this.props.numVars + 1) * i),
          this.props.numVars + 1
        );
      }

      this.setState({ plotRevision: this.state.plotRevision + 1 });
    }

    if (!this.stopAnimation) {
      window.requestAnimationFrame(this.updateChart.bind(this));
    }
  }

From here, it is rendered using:

render() {
    const data = [
      {
        name: 'Backtracks',
        type: 'scattergl',
        mode: 'lines',
        y: this.currentBacktracksPerLevel,
      },
    ];
    for (let i = 0; i < this.props.algoOrder.length; i++) {
      const [line, algo] = this.props.algoOrder[i];
      data.push({
        name: `Algo ${algo} ${this.props.lineLabels[line]}`,
       type: 'scattergl',
        mode: 'lines',
        y: this.currentAlgoFires[i],
        yaxis: 'y2',
      });
    }

    let rangeAlgoMax = 1;
    for (let i = 0; i < this.currentAlgoFires.length; i++) {
      for (let j = 0; j < this.currentAlgoFires[i].length; j++) {
        rangeAlgoMax = Math.max(rangeAlgoMax, this.currentAlgoFires[i][j]);
      }
    }

    let rangeBtMax = 1;
    for (let i = 0; i < this.currentBacktracksPerLevel.length; i++) {
      rangeBtMax = Math.max(rangeBtMax, this.currentBacktracksPerLevel[i]);
    }

    eturn (
      <div
        className={styles['backtrack-window']}
        ref={(el) => { this.container = el; }}
      >
        <Plot
          className={styles['backtrack-graph']}
          ref={(el) => { this.plot = el; }}
          layout={{
            width: this.state.width,
            height: this.state.height,
            xaxis: {
              title: 'Search Level',
              range: [0, this.props.numVars + 1],
            },
            yaxis: {
              title: 'Backtracks Per Level',
              range: [0, rangeBtMax * 1.03],
            },
            yaxis2: {
              title: 'Algo Fires',
              range: [0, rangeAlgoMax * 1.03],
              overlaying: 'y',
              side: 'right',
            },
            legend: {
              orientation: 'h',
              y: 1.2,
            },
            margin: {
              l: 45,
              r: 45,
              b: 40,
              t: 15,
            },
          }}
          revision={this.plotRevision}
          data={data}
       />
      </div>
    );
  }

The timeline graph is created much in the same way, but uses a lot more data that is static. It shows the entire aggregation, which is not updated during animation, and attempts to show a vertical line at a point, representing the current time in the animation. However, whenever I enable the line, it slows down a lot and I haven't seen it yet. Here is the code for the important parts of the timeline graph:

  updateChart = () => {
    if (this.hasUpdated) {
      this.hasUpdated = false;

      this.setState({ plotRevision: this.state.plotRevision + 1 });
    }

    if (!this.stopAnimating) {
      window.requestAnimationFrame(this.updateChart.bind(this));
    }
  }

  render() {
    const data = [
      {
        name: 'Threshold',
        type: 'scattergl',
        mode: 'lines',
        x: this.props.thresholdsTime,
        y: this.props.thresholds,
        side: 'above',
      },
      {
        name: 'Backtracks',
        type: 'scattergl',
        mode: 'lines',
        x: this.props.backtracksTime,
        y: this.props.backtracks,
      },
      {
        name: 'Current Time',
        type: 'scattergl',
        mode: 'lines',
        x: [this.props.currentTime, this.props.currentTime],
        y: [0, 1],
        yaxis: 'y2',
      },
    ];

    return (
      <div className={styles['threshold-window']} ref={(el) => { this.container = el; }}>
        <Plot
          divId={`backtracks-${this.props.name}`}
          className={styles['threshold-graph']}
          ref={(el) => { this.plot = el; }}
          layout={{
            width: this.state.width,
            height: this.state.height,
            yaxis: {
              fixedrange: true,
            },
            yaxis2: {
              side: 'right',
              range: [0, 1],
            },
            margin: {
              l: 35,
              r: 15,
              b: 20,
              t: 15,
            },
            legend: {
              orientation: 'h',
              y: 1,
            },
          }}
          revision={this.state.plotRevision}
          data={data}
        />
      </div>
    );
  }

I'm also looking for overall ways of improving this sort of animation constantly, since it's my first time doing such large scale animations, so if you have any suggestions, even tangential to this issue, that would be great.

Architectural decisions

Nothing particularly actionable here. Just some implementation notes, to be expanded and elaborated upon as we go.

plotly.js-react-editor:

  • markup language will use react's declarative nature rather than tacking on an extra layer of JSON that is processed into JSX. Which, as ben points out, would be declarative on top of declarative, which is a bit redundant. Based on discussion, something more like
    <Panel title="axis" >
      <Slider attr="range[0]"/>
      <RadioToggle attr="axis.type"/>
    </Panel>
    
    would seem preferable, in addition to being equally straightforward, closer to the implementation, and more extensible.
  • pull in components from existing workspace editor while avoiding GenericStyleWidget-style component types.
  • flat directory structure to avoid including ../../../app/views/components/widgets/numerical/slider sort of names or @widgets/numerical/slider sort of indirection.

plotly.js-react

  • Take a pragmatic middle-of-the-road reactive approach in which the change is made in-place and then the callback event is really a notification of the change rather than a purely one-way down-the-tree change.

plotly.js

  • Plotly.react to permit either a state or a diff?
  • Emits plotly_change event with specific details about the value of what was changed?

useResizeHandler no longer works correctly

After latest plotly.js update (1.34), plots with useResizeHandler prop are no longer resized with the surrounding div. They may still resize correctly when e.g. window size is changed.

See CodePen example

Seems to be related to the use of the Plotly.react method, since it still seems to work correctly when I use my own Plotly.react implementation.

onUpdate and onInitialized shouldn't pass a DOM element

Currently, the way the onUpdate and onInitialized callbacks are sending updates back up is by passing this.el, a.k.a. the graphDiv / gd.

This has created some awkward breakages of the React lifecycle because now instead of passing plain prop objects back up, there's a whole DOM element with hidden extra data smuggled aboard (_fullData, _fullLayout, the element ref itself, possibly more undocumented deps…?) being passed around instead.

The updated data and layout objects should be sent separately, either as individual callback params, or within a plain object wrapper. If the additional values (graphDiv, _fullData, _fullLayout, etc…) are still important dependencies that needs to be passed back up by the callback, then they should be broken out into their own unique params / wrapper keys. Then at least these advanced dependencies can be properly documented.

For example, react-plotly.js-editor has difficult state management because it's been coded to rely on the graphDiv exposed by the callbacks, instead of individual dependencies (data, layout, _fullData, _fullLayout, _context).

Error while plotting after React update

Under certain circumstances, after a React update, the <Plot ../> component will throw the following error:

factory.js:131 Error while plotting: Error: DOM element provided is null or undefined
    at Object../node_modules/plotly.js/src/lib/get_graph_div.js.module.exports [as getGraphDiv] (get_graph_div.js:32)
    at Object../node_modules/plotly.js/src/plot_api/plot_api.js.Plotly.react (plot_api.js:2222)
    at factory.js:107
    at <anonymous>

I added some logging into factory.js to try and debug (modified factory.js attached below). Here's the output:

screen shot 2018-02-25 at 5 09 02 pm

My hypothesis is that if Reacts attempts to update the component quickly enough, the promise scheduled in willComponentUpdate (https://github.com/plotly/react-plotly.js/blob/master/src/factory.js#L100) may be called after React calls getRef with null and before it gets called again with the newly rendered div.


Chrome 64.0.3282.167 Mac
plotly.js 1.34.0
react-plotly.js 1.6.0

factory.js.txt

React-plotly Svg transform

I'm trying to use react-plotly inside a foreign object within an Svg, this works fine as shown here.
https://codepen.io/anon/pen/eyYjgr

However I would like to move this object using a transform.
<foreignObject id={"TestSvgFO"} width="100%" height="100%" transform="translate(150, 0)" xmlns="http://www.w3.org/2000/svg">

This results in sliding the view window off the plotly graph instead of moving it.
https://codepen.io/anon/pen/qpByMe

Any suggestions on a way to get it to move correctly in an Svg object with a transform?

(edited your links so they work - alexcjohnson)

Full update on Plot data change

I am just starting to work with Plotly as a part of a create react app based project an I wanted to ask a few clarifying questions (plotly.js 1.35.1 and react-plotly.js 1.7.0)

  1. Based on all the documentation I have read and the demo application itself, one needs to eject or directly import plotly.js via a <script> tag to get it to work with create-react-app. However, I have found this latter approach (directly using the demo app) does not work any more as you get an compile error: Module not found: Can't resolve 'plotly.js' when trying to run the demo app. However, I am able to get things to work in a more "standard" fashion by npm installing both plotly.js and react-plotly.js and directly importing Plot from react-plotly.js into my React component. From what I had read in some of the issues, it sounded like moving away from the need for customising the web pack config was planned for early 2018, so maybe what I am seeing is a result of that, but wanted to be sure there was not a hidden gotcha somewhere.

  2. Based on this issue #25, it sounds like the version I am using should be better about doing updated. However, I have found that updating the state of my component (which changes the data in the Plot component) via a click event when zoomed into a specific region causes the whole plot to unzoom. Am i misunderstanding the scope of this new feature (#25) or just making a rookie mistake?


onClick = (data) => {
    let x = data.points[0].x;
    let y = data.points[0].y;
   
    let {selectedPoints} = this.state;
     
    let selectedIndex = selectedPoints.x.indexOf(x)
    if(selectedIndex === -1) {
       newSelected = {
         x:selectedPoints.x.push(x),
         y:selectedPoints.y.push(y)
       }
    } else {
       newSelected = {
          x: selectedPoints.x.delete(selectedIndex),
          y: selectedPoints.y.delete(selectedIndex)
       }
    }

    this.setState({
      selectedPoints:newSelected
    })

  }

render() {
  return (
    <Plot
        data={[
          {
            type: 'scatter',
            mode: 'lines',
            x: plottedData.x,
            y: plottedData.y,
            marker: {color: 'red'}
          },
          {
            type: 'scatter',
            mode: 'markers',
            x: this.state.selectedPoints.x.toJS(),
            y: this.state.selectedPoints.y.toJS(),
            marker: {color: 'blue'}
          },
        ]}
  
        layout={{
          width: 1020,
          height: 540,
          title: 'A Fancy Plot',
          yaxis: {
            showticklabels:false
          }
        }}
        onClick={this.onClick}
        onSelected = {this.onSelect}
      />
  )
}

Tooltip misaligned when using global data object, layout prop and onHover that manipulates state

The tooltip hover functionality gets messed up when the following conditions are met:

  • You got your own data object which isn't reinitialized every time the plot is rendered.
  • You have declared a custom onHover function
  • You update state to get the component to re-render
  • You have defined the layout property in the Plot component

This sandbox reproduces the error
https://codesandbox.io/s/qx5qr2m5x4

Hover one of the points in the plot. The tooltip will be shown briefly and afterwards the rest of the points will be misaligned towards the axes.

Versions used:
plotly.js 1.37.1
react-plotly.js 2.2.0

Tested on:
chrome
edge

Handling state change in component using react-plotly <Plot>

Are state multiples changes supported in combination with onClick events? Here is an example of what I intend to do https://codepen.io/mjhoffmann/pen/qVVEaZ .

  1. Steps to reproduce issue
    Click on one bar, then click on another bar

  2. What I would except to happen
    The caption "Selected ..." should change on every click

  3. What happens instead
    The caption changes only on the first click but not on any further events.

Is this supported? What is the right way to implement this. Many thanks.

Issue with npm install react-plotly.js plotly.js

I am trying to build a prototype with react-plotly.js. I am following tutorial where it says I need to run "npm install react-plotly.js plotly.js". When I run the command, I get below warnings every time and then it eventually fails.

I'm new to NPM and React.js world. Not sure what is the issue here. NPM version is 5.6.0 if that is any help.

Thank you.

npm WARN deprecated [email protected]: Project renamed to HSLuv
npm WARN deprecated [email protected]: This package has been merged with the 'mapbox-gl-style-spec' package
npm WARN deprecated [email protected]: This package has been merged into the 'mapbox-gl-style-spec' package
npm WARN deprecated [email protected]: This package has been moved to @mapbox/mapbox-gl-supported
npm WARN deprecated [email protected]: This module is now under the @mapbox namespace: install @mapbox/shelf-pack instead
npm WARN deprecated [email protected]: This module has moved: please install @mapbox/point-geometry instead
npm WARN deprecated [email protected]: This module has moved: please install @mapbox/vector-tile instead
npm WARN deprecated [email protected]: This module has moved: switch to @mapbox/unitbezier
npm WARN deprecated [email protected]: This module is now under the @mapbox namespace: install @mapbox/whoots-js instead
npm ERR! Error while executing:
npm ERR! C:\Program Files\Git\cmd\git.EXE ls-remote -h -t ssh://[email protected]/mapbox/mapbox-gl-shaders.git
npm ERR!
npm ERR! ssh: connect to host github.com port 22: Connection timed out
npm ERR! fatal: Could not read from remote repository.
npm ERR!
npm ERR! Please make sure you have the correct access rights
npm ERR! and the repository exists.
npm ERR!
npm ERR! exited with error code: 128

TODO list

  • remove class properties transform from src 😞
  • have it look for Plotly.react
  • lint (using prettier)
  • set up build/lib for distribution
  • add animation
  • frames
  • tests (added jest; needs lots more tests)
  • decide on handling of two-way binding (zoom, pan changing, e.g., xaxis.range)
  • take down temporary netlify site
  • publish to npm
  • production cleanup
  • test scripts on windows
  • publish dummy repo to prevent typosquatting: plotlyjs-react or plotly.js-react, whichever doesn't get used.
  • close related issues: plotly/plotly.js#1850 plotly/plotly.js#204

Updates to pie chart data require click on legend to update properly

First render works fine. When I update the data prop, the chart changes, but incorrectly - it shows just one label/group with 100% portion of the pie. At this point, if I click on the legend to toggle the trace, the plot updates and works correctly. Any subsequent data prop updates will generate the same behavior; clicking on the legend always fixes it.

I have the same chart in bar chart form, responding to the same data with changes at the same time. Bar chart updates OK. Using react-plotly.js 1.7.0 and plotly.js 1.35.2, loaded via script tag.

Prior to today, I had been running plotly.js 1.31.2 - it was working on that version of plotly.js. The project I am currently working on is a re-write of a jquery app to a react app. I tested the same pie chart on the jquery app with plotly.js 1.35.2 and it was able to interact fine - so it seems that this problem is an interaction between 1.35.2 and react-plotly.js

Publish

This will soon be published. Here are the choices:

  1. A single module will export both the version with plotly and as a factory.

    import PlotComponent from 'react-plotly.js'

    Or, alternatively,

    import Plotly from 'plotly.js'
    const EquivalentPlotComponent = factory(Plotly)

    This means plotly.js will be a peer dependency of react-plotly.js. I learned today that peer dependencies are optional and just give a warning if not found. So the usage will either be that you import the factory and create your own, based on your own version of plotly, or that you import the component and it's up to you to npm install plotly.js so that it's available.
    See also:

  2. Description will be A Plotly.js react component from Plotly.

/cc @bpostlethwaite @etpinard @monfera @nicolaskruchten

bar-chart animation on loading

I can't seem to find the ref doc on how to animate bar-chart on page load with react-plotly.js. Most of the animation doc is under Plotly.js that uses Plotly.animate() method to animate the graph. How can I do something similar in react code?

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.