Asking
Asking

Reputation: 4172

Add data in pie chart using D3

I have an application where I use d3.

import React, { useState } from "react";
import ReactDOM from "react-dom";
import * as d3 from "d3";

import Pie from "./PieGraph";

import "./styles.css";

function App() {
  const [data, setData] = useState([
    {
      value: 25
    },
    {
      value: 59
    },
    {
      value: 77
    }
  ]);

  return (
    <div className="App">
      <h1>Pie Chart with React & D3</h1>
      <div></div>
      <div className="piechart">
        <Pie
          data={data}
          width={200}
          height={200}
          innerRadius={60}
          outerRadius={100}
        />
      </div>
    </div>
  );
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

I want to add additional data in chart near numbers, like:

The code for what I have now is here

Question: How to add near numbers, inside chart, a text like I described above?

Upvotes: 0

Views: 172

Answers (1)

Ruben Helsloot
Ruben Helsloot

Reputation: 13129

Supposing you can change PieGraph.js yourself, I'd do the following:

  1. Change Arc to accept data with a value and a label

piegraph.js

const Arc = ({ data, index, createArc, colors, format }) => (
  <g key={index} className="arc">
    <path className="arc" d={createArc(data)} fill={colors(index)} />
    <text
      transform={`translate(${createArc.centroid(data)})`}
      textAnchor="middle"
      fill="white"
      fontSize="10"
    >
      // Here is the change
      {data.format !== undefined ? data.format : format(data.value)}
    </text>
  </g>
);
  1. Change the data you pass to the Pie

index.js

const [data, setData] = useState([
    {
      value: 25,
      label: '25 apples',
    },
    {
      value: 59,
      label: '',
    },
    {
      value: 77
    }
  ]);

Now, the first one has the label '25 apples', the second one has no label and the third one has label 77.00, as was the case already.

Upvotes: 1

Related Questions