Have you ever wanted to create and display graphics in your React app, or do you find it difficult to do so with your current library? If so, this article is just what you need: We’ll look at Plotly and how to take advantage of it in the React application.
Plotly is a free open source data visualization framework that provides a variety of plotting types, such as line graphs, scatter graphs, histograms, Cox graphs, and more.
By enabling us to endlessly customize our diagrams, we can make our diagrams more relevant to others and easier to understand. Plotly is currently only available for Python, R, Julia, Matlab, F# and Javascript applications.
The premise condition
To follow this tutorial, you need the following.
- Working knowledge of React
- Have a good understanding of how diagrams work
- Plotly library for building charts
- The Chakra UI for creating data fields to animate our chart.
To install Plotly and Chakra, run the following command on your terminal.
npm install react-plotly.js plotly.js
npm i @chakra-ui/react @emotion/react@^11 @emotion/styled@^11 framer-motion@^4
Copy the code
How does Plotly work
In Plotly, the user passes the configuration of data points and graphs or charts to the Plot component.
<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'} } />
Copy the code
In the image below, we have two different graphs in the chart: a bar chart and a scatter chart. To achieve this, we use JSON format to pass the two graphs, along with their data points and configurations, as items in the list to the data items in the Plot component.
The above example is a static bar chart and scatter chart, and we pass the data directly to the props. Later in this tutorial, we’ll look at a more dynamic approach to creating graphics.
Plotly different types of graphs and charts
Plotly goes beyond simple bar and scatter charts. We’ll review other diagrams we can implement with Plotly and how to use them in React.
Group bar chart
A grouping bar chart compares two different data points of the same data set. Let’s look at how to build it with Plotly.
const GroupedBarChart = (props) =>{
var plot1 = {
x: ["Microwave", "Washing Machine", "Tv", "Vacuum Cleaner", "Hair Dryer"],
y: [4, 5, 6, 1, 4],
name: "2016",
type: "bar",
};
var plot2 = {
x: ["Microwave", "Washing Machine", "Tv", "Vacuum Cleaner", "Hair Dryer"],
y: [12, 3, 5, 6, 2],
name: "2017",
type: "bar",
};
var data = [plot1, plot2];
return(
<Plot
data={data}
layout={ {width: 500, height: 500, title: 'Electronics Prices 2016/2017'} } />
)
}
Copy the code
In the code above, we create two bar graph graphs (PLT1 and ploT2), then group them with the same X value and pass both graphs to the data props of the Plot component. In this way, we can group two or more bar graphs.
The code then outputs the diagram below.
The pie chart
Pie charts compare different areas of a particular data set or data set. Our pie chart example will compare a class of students’ favorite color choices.
Let’s see how we can do this with Plotly.
const PieChart = (props) =>{
var data = [
{
values: [112, 454, 65, 544],
labels: ["Blue", "Red", "Yellow", "Orange"],
type: "pie",
},
];
return(
<Plot
data={data}
layout={ {width: 500, height: 500, title: 'Favourite Colours In A Class'} } />
)
}
Copy the code
In the code above, we pass labels,values, and Type to the chart, containing the color, number of students, and type of the chart, respectively.
Area chart
An area diagram describes the evolution of one or more quantities over time, comparable to a diagram. In area and line plots, data points are plotted and then connected by line segments to illustrate the value of a quantity over time.
However, area plots are different from line plots because the area between the X-axis and line is filled with color or shadow.
Area maps are a good choice when we want to show a pattern that changes over time, but are not concerned with providing accurate values.
To build up an area map with Plotly, we simply add a value to the scatter plot’s fill property. In this example, we will build a regional map to find price trends between suppliers and suppliers.
const AreaChart = (props) =>{
var data = [
{
x: [1, 2, 3, 4],
y: [0, 2, 3, 5],
fill: 'tozeroy',
type: 'scatter',
name: 'Vendor'
},
{
x: [1, 2, 3, 4],
y: [3, 5, 1, 7],
fill: 'tonexty',
type: 'scatter',
name: 'Provider'
}
];
return(
<Plot
data={data}
layout={ {width: 500, height: 500, title: 'Area Chart'} } />
)
}
Copy the code
The output of the code looks like this.
form
Tables organize information in rows and columns, and their cells can be easily compared and contrasted. To create a table with Plotly, we must pass the title and cell values, as shown in the code below.
In this example, we will compare the cost of some basic expenses.
const Table= (props) =>{
const values = [
["Books", "Clothes", "Medicals"],
["$22", "$190", "$516"],
];
const headers = [["<b> Item </b>"], ["<b> Expenditure </b>"]];
const data = [
{
type: "table",
header: {
values: headers,
align: "center",
},
cells: {
values: values,
align: "center",
},
},
];
return(
<Plot
data={data}
layout={ {width: 500, height: 500, title: 'Table'} } />
)
}
Copy the code
By passing two headings and a list for each heading to our expense table, the contents of the first list occupy the cells under the first heading, and the contents of the second list occupy the cells under the second heading.
The code is then printed as follows.
We can also style our tables.
const Table= (props) =>{
const values = [
["Books", "Clothes", "Medicals"],
["$22", "$190", "$516"],
];
const headers = [["<b> Item </b>"], ["<b> Expenditure </b>"]];
const data = [
{
type: "table",
header: {
values: headers,
align: "center",
fill: { color: "#2849cc" },
font: { color: "white", size: 20 },
},
cells: {
values: values,
align: "center",
font: { family: "Ubuntu" },
},
},
];
return(
<Plot
data={data}
layout={ {width: 500, height: 500, title: 'Table'} } />
)
}
Copy the code
Create dynamic charts with Plotly
Now that we’ve learned how to create graphs, drawings, and charts, let’s learn how to make them dynamic. To do this, we must update the drawn data with the React state. Let’s look at what a dynamic scatter diagram looks like.
import Plot from 'react-plotly.js'; import React, { useState } from "react" import { HStack,Input, Text} from "@chakra-ui/react" const GraphCard = (props) =>{const [scatter, setScatter] = useState({x: [1,2,3], y: ,5,3 [2], type: 'scatter' mode: 'lines + markers' marker: {color:' red '},}); const [ data, setData ] = useState([scatter]); const handleChange = (i,j,e) => { const newScatter = {... scatter}; newScatter\[i\][j]=parseInt(e.target.value); setScatter(newScatter); setData([scatter]); } return( <> <Plot data={[{ x: \[data[0\]["x"]\[0],data[0\]["x"]\[1],data[0\]["x"][2]], y: \[data[0\]["y"]\[0],data[0\]["y"]\[1],data[0\]["y"][2]], type: 'scatter', mode: 'lines+markers', marker: {color: 'red'}, }]} layout={ {width: 500, height: 500, title: 'A Dynamic Fancy Plot'} } /> <HStack align="center" marginTop="2rem" padding="2rem"> <Text fontSize="md">X1</Text> <Input type="number" placeholder={data\[0\]["x"][0]} onChange={(e) => handleChange("x",0,e)}/> <Text fontSize="md">X2</Text> <Input type="number" placeholder={data\[0\]["x"][1]} onChange={(e) => handleChange("x",1,e)}/> <Text fontSize="md">X3</Text> <Input type="number" placeholder={data\[0\]["x"][2]} onChange={(e) => handleChange("x",2,e)}/> <Text fontSize="md">Y1</Text> <Input type="number" placeholder={data\[0\]["y"][0]} onChange={(e) => handleChange("y",0,e)}/> <Text fontSize="md">Y2</Text> <Input type="number" placeholder={data\[0\]["x"][1]} onChange={(e) => handleChange("y",1,e)}/> <Text fontSize="md">Y3</Text> <Input type="number" placeholder={data\[0\]["x"][2]} onChange={(e) => handleChange("y",2,e)}/> </HStack> </> ) } export default GraphCard;Copy the code
In the code above, we built our user interface using the Chakra UI library, defined our scatter graph data in a Scatter state and wrapped it in a Data list state.
By creating a handleChange function and attaching it to our Chakra input onChange event, the handleChange function keeps track of input changes at all data points and updates the data in the graph to make the scatter graph dynamic.
Here is the output of the above code.
Customize the chart with Plotly
Here we’ll learn how to configure and customize our diagrams for better use and experience.
Mark shaft
To label the X and y axes of your drawing, use the Xaxis and yaxis keys in the layout properties, as shown in the code below.
<Plot data={data} layout={ {width: 500, height: 500, title: 'A Dynamic Fancy Plot', xaxis:{title:"Music"}, yaxis:{title:"Sales"}} } />
Copy the code
Doing so displays a graph with a “music” and “sales” axis.
Scroll to zoom
This function allows the user to scale the chart of a scatter plot to make it easier to navigate through the data. We can use it to examine or get a more detailed view of the layout. To achieve scrolling zoom in our diagram, set scrollZoom in the Config property.
<Plot data={data} layout={ {width: 500, height: 500, title: 'A Dynamic Fancy Plot', xaxis:{title:"Music"}, yaxis:{title:"Sales"}}} config={{scrollZoom:true}}/>
Copy the code
Add the legend name
In cases where we have two graphs on the same graph, we must mark them with legends. To do this, set the name property of the data where we defined it. Let’s look at an example of a graph with a scatter plot and a bar plot.
<Plot
data={[
{
x: [1, 2, 3],
y: [2, 6, 3],
type: 'scatter',
mode: 'lines+markers',
marker: {color: 'red'},
name: "scatterplot"
},
{type: 'bar', x: [1, 2, 3], y: [2, 5, 3], name:"bar chart},
]}
layout={ {width: 500, height: 500, title: 'A Fancy Plot'} } />
Copy the code
In the code above, we set a name value for each dataset in the list. This is done to label the data sets and display them on the right side of the graph.
conclusion
This article will teach you how to create charts, graphs, and action graphs with Plotly. You can read more about Plotly’s official documentation here. If you have any questions, don’t hesitate to contact me on Twitter: @Lordchuks3.
The postUsing Plotly in React to build dynamic charts and graphsappeared first onLogRocket Blog.