In this post we will review usage of plotly based scatter plot in a react application.
We start by creating the react&redux template:
npx create-react-app my-app --template redux
Next we add the the react plotly library:
npm i -s react-plotly.js
And update the application to show our scatter plot:
import React from 'react'
import './App.css'
import createPlotlyComponent from 'react-plotly.js/factory'
function App() {
const Plot = createPlotlyComponent(window.Plotly)
return (
<div className="App">
<header className="App-header">
<Plot
data={[
{
x: [1, 2, 3, 1],
y: [1, 2, 3, 5],
text: ['p1', 'p2', 'p3', 'p4'],
type: 'scatter',
mode: 'lines+markers',
marker: {
color: 'green',
size: 10,
},
},
]}
layout={{
width: 800,
height: 600,
}
}
/>
</header>
</div>
)
}
export default App
Notice that we do not use the plotly component directly. This is since we want to reduce the size of the compiled application bundle. Instead of including the entire bundle of plotly and d3, we will download it from the CDN using the following update in the application HTML file. The npm will still download all of the bundle dependencies, but the webpack will include only the used resources, and hence the plotly and the d3 will not be included in the bundle.
index.html
<script crossorigin src="https://cdn.plot.ly/plotly-latest.min.js"></script>
And the result is a nice scatter plot:
Final Note
We have reviewed the process of adding a scatter plot to a react application. Scatter plot can be used to show, for example, location overtime. We have specifically used it to show mouse movement.
No comments:
Post a Comment