Part 1 of 3: Plotly in React – Real time data visualization

How to display real-time, dynamically updated data using plotly in React.

https://media.giphy.com/media/JhXhcb061UiHPAGCqL/giphy.gif

Are you gearing up to write a new data app?
Does your business contain critically huge amounts of data that are interpreted best when visualized?
Do you want to make your data points interactive for the user without writing a ton of code?

Consider using plotly.

Plotly?

Ploty is a popular, feature-rich solution for writing data visualization apps with relatively small amounts of code. Scatter plot charts, bar charts, 3D charts, maps, and much more are all possible with plotly.

In this article…

I’ll be showing you the “Hello, World” of a plotly react app, along with making the plot display dynamic, real-time results.


What you should know already:
  • Good understanding of Javascript
  • Basic understanding of Typescript (this app will be in Typescript!)
  • Intermediate understanding of React and React hooks


Steps in creating this real-time data plotly component:
  • Create the app in codesandbox.io
  • Import the required packages
  • Create basic Plot component
  • Add hard-coded data to Plot component
  • Create state variable to be passed to Plot component
  • Continuous update state variable

Create app in codesandbox.io

Begin by creating a codesandbox.io account, if you don’t already have one. Select “Create” at the top to create a new sandbox, and select React Typescript.

You will be given a new, blank typescript React project like this one:

Import the required packages

On the left you’ll see an text box where you can select npm packages to install in your app along with packages that come pre-loaded with your app.

Add the following plotly related packages:

  • @types/react-plotly.js
  • react-plotly.js
  • plotly.js
  • Create basic Plot component

    In App.tsx, replace the existing code in that file with this:

    import "./styles.css";
    import Plot from "react-plotly.js";
     
    export default function App() {
     return (
       <div className="App">
         <Plot />
       </div>
     );
    }
    
    You should notice a few things:

  • We’re importing the default Plot component from ‘react-plotly.js’
  • We’re using the Plot component in our JSX
  • The output on the right has been replaced with a basic graph!
  • Note: There might be a typescript error about missing required props. We’ll resolve those in the next step.

    Add hard-coded data to Plot component

    In the Plot component, add two props with values:

    <Plot
           data={[{ x: [1, 2, 3, 4, 5], y: [4, 1, 3, 8, 5] }]}
           layout={{ title: "My Test App" }}
         />
    
    The `data` prop contains the data to be displayed along with associated x and y coordinates. The `layout` prop contains metadata to be displayed on a different layer as the data such as title, shapes, annotations, etc… We’ll learn more about the layout prop in Part 2.

    You’ll also notice that the variable passed to data is an array–this allows more than one set of data to be displayed at the same time:

    <Plot
           data={[
             { x: [1, 2, 3, 4, 5], y: [4, 1, 3, 8, 5] },
             { x: [1.5, 2.5, 3.5], y: [10, 11, 12] }
           ]}
           layout={{ title: "My Test App" }}
         />
    

    Create a state variable to be passed to Plot component

    Now create a “data” state hook to pass to the data prop, like this:

    import React from "react";
    import "./styles.css";
    import Plot from "react-plotly.js";
     
    const count = 30;
     
    const startingNumbers = Array(count)
     .fill(1)
     .map((_, i) => i);
     
    export default function App() {
     const [data, setData] = React.useState({
       x: startingNumbers,
       y: startingNumbers
     });
     
     return (
       <div className="App">
         <Plot
           data={[data]}
           layout={{
             title: "Real-time Data App",
             xaxis: { range: [-5, count] },
             yaxis: { range: [-5, count] }
           }}
         />
       </div>
     );
    }
     
    
    This is the variable that we will continually update and see the results in real-time in our plotly chart.

    A few things to notice about this new code:
  • I’m using some nifty javascript array functions to create an array of 30 numbers, all numbered 1 through 30 instead of typing one out like this: [1,2,3,4…].
  • In the layout prop you can see that I dictate how much of the graph I want to show. Not setting these values causes plotly to autosize the x and y bounds to fit the line. I’m passing in -5 as the x and y lower bounds so I can see a bit more than I would if the graph was autosizing.
  • Continuously update state variable

    Finally, add this useEffect hook inside your App component. This will continually update the data state hook we just made.

     React.useEffect(() => {
       const interval = setInterval(() => {
         setData((prev) => {
           return {
             x: prev.x,
             y: [...prev.y.slice(1), Math.floor(Math.random() * count)]
           };
         });
       }, 1000);
     
       return () => {
         clearInterval(interval);
       };
     }, []);
    
    You can see that the useEffect is taking the existing array of data, slicing off the first value while also adding a random value at the end. This mimics how data might come in from a server or other source.
    https://media.giphy.com/media/JhXhcb061UiHPAGCqL/giphy.gif

    Extras:

  • If you want to modify the number of points on the screen, increase the value of the `count` variable at the top.
  • The 2nd parameter passed to the setInterval function is the millisecond interval at which the function is run. The smaller the number, the more frequently the variable will be updated, which in turn will cause the plot to updated more frequently as well.
  • You can see an already built sandbox here: https://codesandbox.io/s/plotly-realtime-dataviz-blogpost-vio9p1?file=/src/App.tsx

    Conclusion

    In the next article for this 3 part series on Plotly, I’ll be showing you how to create a scatter plot and how to allow the user to make multiple selections.

    3-Part Series:

    • Part 1 of 3: Plotly in React – Real time data visualization
    • Part 2 of 3: Plotly in React – Display Multiple Selections with Annotations
    • Part 3 of 3: Part 3 of 3: Plotly in React – Merge Multiple Selections using polygon-clipping

    About Intertech

    Intertech is a Software Development Consulting Firm that provides single and multiple turnkey software development teams, available on your schedule and configured to achieve success as defined by your requirements independently or in co-development with your team. Intertech teams combine proven full-stack, DevOps, Agile-experienced lead consultants with Delivery Management, User Experience, Software Development, and QA experts in Business Process Automation (BPA), Microservices, Client- and Server-Side Web Frameworks of multiple technologies, Custom Portal and Dashboard development, Cloud Integration and Migration (Azure and AWS), and so much more. Each Intertech employee leads with the soft skills necessary to explain complex concepts to stakeholders and team members alike and makes your business more efficient, your data more valuable, and your team better. In addition, Intertech is a trusted partner of more than 4000 satisfied customers and has a 99.70% “would recommend” rating.