Create Cool Plots With React and Plotly
Marianna
Posted on February 12, 2022
Today I will show you how to create an interactive plot with React and Plotly library that you can use in your React web apps!
Let's start cooking!π³
Step 1
In this tutorial we will plot 24hr price change of cryptocurrency. To do that we will need an API to get data. I will use Alpha Vantage API to fetch data. You can grab your own API key on their website or just use demo key.
To get data from API we will use fetchData
function:
const fecthData = async () => {
const apiKey = "demo";
const url = `https://www.alphavantage.co/query?function=CRYPTO_INTRADAY&symbol=ETH&market=USD&interval=5min&apikey=${apiKey}`;
return fetch(url)
.then((res) => {
if (res.status === 200) {
return res.json();
}
})
.then((data) => {
return data["Time Series Crypto (5min)"];
});
};
This function is asynchronous because it takes time to retrieve data and we don't want our application to be blocked during this time!
Step 2
Then we need to install Plotly. To do this just run the following command in your terminal:
npm install react-plotly.js plotly.js
After installation import Plotly and React hooks that we will need for state management:
import Plot from "react-plotly.js";
import { useState, useEffect } from "react";
Step 3
We will create functional React component for our app:
export default function App() {
const [data, setData] = useState([]);
const [dataIsLoaded, setDataIsLoaded] = useState(false);
if (dataIsLoaded) {
return <div>Loaded</div>;
} else {
return <div>Loading...</div>;
}
We will show our plot only after our data is loaded. To do this we will use Boolean variable dataIsLoaded
that will be set to true when we get data. Variable data
will be used to store retrieved data.
Step 4
We want to fetch data only once when the app is loaded. To make this happen we will use React useEffect
hook, everything we write inside this hook will be executed only once:
useEffect(() => {
fecthData().then((res) => {
setData(res);
setDataIsLoaded(true);
});
}, []);
We use .then
with our fetchData()
because it returns Promise and after this Promise will be returned we will set our data variable to the response from the API. After that we will set dataIsLoaded
to true to render our plot.
Step 5
To be able to show our plot we need x
and y
variables: x
for x axis and y
for y axis:
const X = Object.keys(data);
const Y = X.map((date) => {
return data[date]["1. open"];
});
On x axis we will show the date and on the y axis we will show the open price of ETH.
Step 6
To create a line chart we will use Plot
component with type scatter
and mode lines
. Also we will set some layout options to add title, change range of y axis, background color and font:
if (dataIsLoaded) {
return (
<Plot
data={[
{
x: X,
y: Y,
fill: "tonexty",
type: "scatter",
marker: { color: "#8000DE" }
}
]}
layout={{
width: 500,
height: 300,
title: "ETH-USD",
yaxis: {
range: [2850, 3000],
type: "linear"
},
paper_bgcolor: "rgb(243, 243, 243)",
plot_bgcolor: "#f3f3f3",
family: "Courier New, monospace"
}}
/>
);
}
You should get something like this:
And to add fill under plot just use fill
property in data:
data={[
{
x: X,
y: Y,
fill: "tonexty", // add this
type: "scatter",
mode: "lines",
marker: { color: "#8000DE" }
}
]}
You can learn more about different plot types and their attributes on the official Plotly website.
Also you can view all the source code and live demo on my CodeSandBox.
That's all!π
Hope you liked this tutorial and happy coding!
Posted on February 12, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
September 14, 2024