d3 Charts In React.js

In this article, we learn how to implement d3 charts in our React js project.

First, we need to import the d3 chart dependency.

npm install react-charts-d3

Now we learn how to create a Line chart using this library.

so, we need to take the data that we want to pass in the chart.

const data = [
    { key: 'Group 1', values: [{ x: 'A', y: 23 }, { x: 'B', y: 8 }] },
    { key: 'Group 2', values: [{ x: 'A', y: 15 }, { x: 'B', y: 37 }] },
];

Now we want to import LineChart in react-charts-d3 and pass the data into that.

<LineChart data={data} />

Now we learn how to create a Pie chart using this library.

Here we take the same line chart data and then import PieChart

const piedata = [
    { label: 'Group 1', value: 23 },
    { label: 'Group 2', value: 15 },
];

<PieChart data={piedata} />

Same as we create a Bubble chart using this library.

So, same as we have done above take data and pass it into imported BubbleChart in react-charts-d3.

const bubbledata = [
    { key: 'Group 1', values: [{ x: 'A', y: 23, r: 4 }, { x: 'B', y: 8, r: 19 }] },
    { key: 'Group 2', values: [{ x: 'A', y: 15, r: 11 }, { x: 'B', y: 37, r: 21 }] },
];

<BubbleChart data={bubbledata} />

Same as we create also AreaChart, barChart, and ScatterChart.

So, my app.js looks like this,

import React from 'react'
import { AreaChart, BarChart, BubbleChart, LineChart, PieChart, ScatterChart } from 'react-charts-d3';

const App = () => {
  const data = [
    { key: 'Group 1', values: [{ x: 'A', y: 23 }, { x: 'B', y: 8 }] },
    { key: 'Group 2', values: [{ x: 'A', y: 15 }, { x: 'B', y: 37 }] },
  ];

  const piedata = [
    { label: 'Group 1', value: 23 },
    { label: 'Group 2', value: 15 },
  ];

  const bubbledata = [
    { key: 'Group 1', values: [{ x: 'A', y: 23, r: 4 }, { x: 'B', y: 8, r: 19 }] },
    { key: 'Group 2', values: [{ x: 'A', y: 15, r: 11 }, { x: 'B', y: 37, r: 21 }] },
  ];

  return (
    <div>
      <div style={{ display: 'flex' }}>
        <div>
          AreaChart
          <AreaChart data={data} />
        </div>
        <div>
          BarChart
          <BarChart data={data} />
        </div>
        <div>
          LineChart
          <LineChart data={data} />
        </div>
      </div>
      <div style={{ display: 'flex' }}>
        <div>
          ScatterChart
          <ScatterChart data={data} />
        </div>
        <div>
          PieChart
          <PieChart data={piedata} />
        </div>
        <div>
          BubbleChart
          <BubbleChart data={bubbledata} />
        </div>
      </div>
    </div >
  )
}

export default App

Output:-

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories