The Victory lets us add charts and data visualization into our React app.
In this article, we’ll look at how to add charts into our React app with Nivo.
Sankey Diagram
Nivo comes with code to let us add a Sankey diagram into our React app.
To install the required packages, we run:
npm i @nivo/sankey
Then we can create the diagram by writing:
import React from "react";
import { ResponsiveSankey } from "@nivo/sankey";
const data = {
nodes: [
{
id: "John",
color: "hsl(355, 70%, 50%)"
},
{
id: "Raoul",
color: "hsl(276, 70%, 50%)"
},
{
id: "Jane",
color: "hsl(331, 70%, 50%)"
},
{
id: "Marcel",
color: "hsl(32, 70%, 50%)"
},
{
id: "Ibrahim",
color: "hsl(331, 70%, 50%)"
},
{
id: "Junko",
color: "hsl(71, 70%, 50%)"
}
],
links: [
{
source: "Ibrahim",
target: "John",
value: 27
},
{
source: "Ibrahim",
target: "Marcel",
value: 151
},
{
source: "John",
target: "Jane",
value: 172
},
{
source: "John",
target: "Raoul",
value: 27
}
]
};
const MyResponsiveSankey = ({ data }) => (
<ResponsiveSankey
data={data}
margin={{ top: 40, right: 160, bottom: 40, left: 50 }}
align="justify"
colors={{ scheme: "category10" }}
nodeOpacity={1}
nodeThickness={18}
nodeInnerPadding={3}
nodeSpacing={24}
nodeBorderWidth={0}
nodeBorderColor={{ from: "color", modifiers: [["darker", 0.8]] }}
linkOpacity={0.5}
linkHoverOthersOpacity={0.1}
enableLinkGradient={true}
labelPosition="outside"
labelOrientation="vertical"
labelPadding={16}
labelTextColor={{ from: "color", modifiers: [["darker", 1]] }}
legends={[
{
anchor: "bottom-right",
direction: "column",
translateX: 130,
itemWidth: 100,
itemHeight: 14,
itemDirection: "right-to-left",
itemsSpacing: 2,
itemTextColor: "#999",
symbolSize: 14,
effects: [
{
on: "hover",
style: {
itemTextColor: "#000"
}
}
]
}
]}
/>
);
export default function App() {
return (
<div style={{ width: 400, height: 300 }}>
<MyResponsiveSankey data={data} />
</div>
);
}
We define the data we’ll render in the data
object.
Then in the MyResponsiveSankey
component, we render the ResponsiveSankey
component to render the Sankey diagram.
We set the node styles with the nodeOpacity
, nodeThickness
, nodeInnerPadding
, nodeSpacing
, nodeBorderWidth
, and nodeBorderColor
props.
linkOpacity
has the opacity of the link that we’re hovering over.
linkHoverOthersOpacity
has the opacity of the link that we aren’t hovering over.
labelPosition
has the label position.
labelOrientation
has the label orientation.
labelTextColor
has the label text color scheme.
legends
has the legend settings.
We set the item dimensions and translation.
symbolSize
has the legend symbol size in pixels.
effects
is set to have the hover effect and change the text of the item we hover over with itemTextColor
.
Then in App
, we set the width and height of the div so we can render the chart.
Conclusion
We can add a Sankey diagram into our React app with Nivo.