Exploring Data Visualization with D3.js and Nivo

Ashish sahooAshish sahoo
6 min read

Introduction:

In today's digital landscape, effective data visualization is crucial for understanding and communicating complex information like it's for business intelligence, scientific research, or storytelling, data visualization tools play a crucial role in helping us make sense of complex datasets.

Among the Excess Surplus of tools available, D3.js (Data-Driven Documents) and Nivo stand out as powerful libraries for crafting visually stunning and interactive graphics.

This blog explores the features, pros and cons, and practical examples of both D3.js and Nivo to help you choose the right tool for your data visualization needs.

Section 1: Understanding D3.js

D3.js, short for Data-Driven Documents, is a powerful JavaScript library for creating dynamic, interactive data visualizations in web browsers. D3.js enables developers to create custom visualizations tailored to specific needs and apply data-driven transformations to generate visual representations of the data. It provides a comprehensive toolkit for manipulating documents based on data, making it ideal for building custom and highly expressive visualizations.

Here are some of the things you can do with D3:

  • Create bar charts, line charts, pie charts, and other common chart types.

  • Create more complex visualizations, such as maps, heatmaps, and treemaps.

  • Add interactivity to your visualizations, such as panning, zooming, and brushing.

Drawbacks:

  • we need to write the code everything from scartch to create charts

  • there is no pre-built, high-level components, requiring custom solutions for common visualization tasks.

  • we need to handle many details manually, which is diffcult to manage code and longer development times.

  • Lack of Official Support that leading to slower bug fixes and less predictability to counter the bug

Installing D3.js in a React Application:

To install D3.js in a React application using npm, you can run the following command in your project directory:

npm install d3

Once D3.js is installed, you can import it into your React component like this:

import * as d3 from 'd3';
// Sample dataset
const data = [10, 20, 30, 40, 50];

// Create SVG container
const svg = d3.select('body')
  .append('svg')
  .attr('width', 400)
  .attr('height', 200);

// Create bars
svg.selectAll('rect')
  .data(data)
  .enter()
  .append('rect')
  .attr('x', (d, i) => i * 50)
  .attr('y', (d) => 200 - d)
  .attr('width', 40)
  .attr('height', (d) => d)
  .attr('fill', 'steelblue');

Section 2: Introducing Nivo

Nivo is a powerful React data visualization library that built on top of D3.js, Nivo abstracts away much of the complexity of D3 to offer a rich set of customizable and responsive components for creating stunning visualizations. Built with React developers in mind, Nivo provides a declarative API and a wide range of ready-to-use chart types, making it easy to create complex visualizations with minimal code.

Features of Nivo:

Declarative API:

Nivo's declarative API allows developers to define visualizations using simple React components, abstracting away much of the complexity of D3.js while maintaining flexibility and customization options.

Rich Set of Components:

Nivo offers a diverse collection of components for various chart types, including line charts, bar charts, pie charts, scatter plots, and more, catering to a wide range of data visualization needs.

Responsive Design:

All Nivo components are designed to be responsive out of the box, ensuring that visualizations adapt gracefully to different screen sizes and devices, providing an optimal viewing experience across desktop and mobile platforms.

Customization:

Nivo provides extensive customization options, allowing developers to fine-tune every aspect of the visualizations, including colors, labels, legends, tooltips, and animations, to match the design and branding requirements of their applications.

Installing Nivo in a React Application:

to install Nivo in a React application using npm, you can run the following command:

npm install @nivo/pie @nivo/bar

Importing Nivo Components in a React Component:

Once Nivo is installed, you can import the desired Nivo components into your React component. For example, if you want to use the bar chart component, you can import it like this:

import { ResponsiveBar } from '@nivo/bar';
  1. Importing Nivo Components in a React Component:

Once Nivo is installed, you can import the desired Nivo components into your React component. For example, if you want to use the bar chart component, you can import it like this:

import { ResponsiveBar } from '@nivo/bar';
import React from "react";
import { ResponsiveBar } from "@nivo/bar";

const data = [
  {
    country: "AD",
    "hot dog": 103,
    "hot dogColor": "hsl(299, 70%, 50%)",
    burger: 153,
    burgerColor: "hsl(31, 70%, 50%)",
    sandwich: 98,
    sandwichColor: "hsl(228, 70%, 50%)",
    kebab: 198,
    kebabColor: "hsl(124, 70%, 50%)",
    fries: 13,
    friesColor: "hsl(17, 70%, 50%)",
    donut: 123,
    donutColor: "hsl(18, 70%, 50%)",
  },
  {
    country: "AE",
    "hot dog": 126,
    "hot dogColor": "hsl(313, 70%, 50%)",
    burger: 167,
    burgerColor: "hsl(354, 70%, 50%)",
    sandwich: 109,
    sandwichColor: "hsl(179, 70%, 50%)",
    kebab: 190,
    kebabColor: "hsl(51, 70%, 50%)",
    fries: 77,
    friesColor: "hsl(313, 70%, 50%)",
    donut: 19,
    donutColor: "hsl(73, 70%, 50%)",
  },
  {
    country: "AF",
    "hot dog": 67,
    "hot dogColor": "hsl(16, 70%, 50%)",
    burger: 25,
    burgerColor: "hsl(265, 70%, 50%)",
    sandwich: 78,
    sandwichColor: "hsl(335, 70%, 50%)",
    kebab: 128,
    kebabColor: "hsl(269, 70%, 50%)",
    fries: 82,
    friesColor: "hsl(20, 70%, 50%)",
    donut: 93,
    donutColor: "hsl(279, 70%, 50%)",
  },
  {
    country: "AG",
    "hot dog": 63,
    "hot dogColor": "hsl(215, 70%, 50%)",
    burger: 197,
    burgerColor: "hsl(191, 70%, 50%)",
    sandwich: 159,
    sandwichColor: "hsl(241, 70%, 50%)",
    kebab: 44,
    kebabColor: "hsl(2, 70%, 50%)",
    fries: 144,
    friesColor: "hsl(147, 70%, 50%)",
    donut: 15,
    donutColor: "hsl(108, 70%, 50%)",
  },
  {
    country: "AI",
    "hot dog": 28,
    "hot dogColor": "hsl(270, 70%, 50%)",
    burger: 37,
    burgerColor: "hsl(172, 70%, 50%)",
    sandwich: 18,
    sandwichColor: "hsl(3, 70%, 50%)",
    kebab: 199,
    kebabColor: "hsl(210, 70%, 50%)",
    fries: 75,
    friesColor: "hsl(294, 70%, 50%)",
    donut: 35,
    donutColor: "hsl(317, 70%, 50%)",
  },


];

const Nivobar = () => {
  return (
    <div style={{ width: "80vw", height: "54vh", margin: "auto" }}>
      <ResponsiveBar
        data={data}
        keys={["hot dog", "burger", "sandwich", "kebab", "fries", "donut"]}
        indexBy="country"
        margin={{ top: 50, right: 130, bottom: 50, left: 60 }}
        padding={0.3}
        valueScale={{ type: "linear" }}
        indexScale={{ type: "band", round: true }}
        colors={{ scheme: "nivo" }}
        defs={[
          {
            id: "dots",
            type: "patternDots",
            background: "inherit",
            color: "#38bcb2",
            size: 4,
            padding: 1,
            stagger: true,
          },
          {
            id: "lines",
            type: "patternLines",
            background: "inherit",
            color: "#eed312",
            rotation: -45,
            lineWidth: 6,
            spacing: 10,
          },
        ]}

        borderColor={{
          from: "color",
          modifiers: [["darker", 1.6]],
        }}
        axisTop={null}
        axisRight={null}
        axisBottom={{
          tickSize: 5,
          tickPadding: 5,
          tickRotation: 0,
          legend: "country",
          legendPosition: "middle",
          legendOffset: 32,
          truncateTickAt: 0,
        }}
        axisLeft={{
          tickSize: 5,
          tickPadding: 5,
          tickRotation: 0,
          legend: "food",
          legendPosition: "middle",
          legendOffset: -40,
          truncateTickAt: 0,
        }}
        labelSkipWidth={12}
        labelSkipHeight={12}
        labelTextColor={{
          from: "color",
          modifiers: [["darker", 1.6]],
        }}
        legends={[
          {
            dataFrom: "keys",
            anchor: "bottom-right",
            direction: "column",
            justify: false,
            translateX: 120,
            translateY: 0,
            itemsSpacing: 2,
            itemWidth: 100,
            itemHeight: 20,
            itemDirection: "left-to-right",
            itemOpacity: 0.85,
            symbolSize: 20,
            effects: [
              {
                on: "hover",
                style: {
                  itemOpacity: 1,
                },
              },
            ],
          },
        ]}
        role="application"
        ariaLabel="Nivo bar chart demo"
        barAriaLabel={(e) =>
          e.id + ": " + e.formattedValue + " in country: " + e.indexValue
        }
      />
    </div>
  );
};

export default Nivobar

Conclusion

Choosing between D3.js and Nivo depends on project requirements and developer preferences. Both empower developers to transform data into compelling visual narratives, driving informed decisions in the ever-evolving landscape of data visualization.

May your visualizations illuminate insights and inspire action. Happy visualizing!

0
Subscribe to my newsletter

Read articles from Ashish sahoo directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Ashish sahoo
Ashish sahoo