20

I'm trying to learn how to use Rechart. The documentation says you can put labels on chart elements, and gives an example of how to do it using 'name' as the label data key.

I've tried to do that in my chart, but it doesn't work.

If i remove the 'label' from the field, then no labels appear. If I keep it, then the only labels that display are the values on the pie chart wedges.

I have a Label with a data key of 'name' (per the docs) but it doesn't render on the chart.

import React, { PureComponent } from 'react';
import {
  ResponsiveContainer, PieChart, Pie, Legend, Label, LabelList
} from 'recharts';

const data = [
  { name: 'Group A', value: 400 }, { name: 'Group B', value: 300 },
  { name: 'Group C', value: 300 }, { name: 'Group D', value: 200 },
];

export default class Example extends PureComponent {
  static jsfiddleUrl = '//jsfiddle.net/alidingling/6okmehja/';

  render() {
    return (
      <div style={{ width: '100%', height: 300 }}>
        <ResponsiveContainer>
          <PieChart>
            <Pie dataKey="value" 
            data={data} 
            fill="#8884d8" 
            Label dataKey="name"    
            />
          </PieChart>
        </ResponsiveContainer>
      </div>
    );
  }
}

How do you add labels to pie charts?

Mel
  • 2,481
  • 26
  • 113
  • 273
  • 1
    Have you tried using `nameKey` attribute to tell Recharts the name of each sector? Moreover, be sure to write `label` and not `Label` (indeed, the second refers to a React component, but I'm pretty sure it is a typo) – Keilath May 12 '19 at 22:45
  • Hi - the rechart docs use uppercase 'Label': http://recharts.org/en-US/api/Label – Mel May 12 '19 at 23:05
  • How would i use nameKey? I tried: Label namekey="name" but it doesn't work – Mel May 12 '19 at 23:05
  • I have also tried; Label value="name" but it doesn't work – Mel May 12 '19 at 23:07
  • I have also tried lower case l as: label nameKey="name" but it prints the data values as labels (as it does when you use the default) – Mel May 12 '19 at 23:09
  • I tried downloading prime react charts to use instead, but that has a config error that says: ./node_modules/primereact/components/chart/Chart.js Module not found: Can't resolve 'chart.js/dist/Chart.js – Mel May 14 '19 at 20:35

3 Answers3

19

For others looking for an answer, this works:

Define a function to render you labels the way you want, some like:

let renderLabel = function(entry) {
    return entry.name;
}

Set the label prop to point to your function:

<Pie label={renderLabel} [ you other properties ]>
[ your content ]
</Pie>
Mel
  • 2,481
  • 26
  • 113
  • 273
8

Sorry for delay, I was finally able to come up with a solution, even if it's not pretty straightforward

const {ResponsiveContainer, PieChart, Pie, Legend} = Recharts;

const data = [{name: 'Group A', value: 400}, {name: 'Group B', value: 300},
                  {name: 'Group C', value: 300}, {name: 'Group D', value: 200}]

const RADIAN = Math.PI / 180;

const renderCustomizedLabel = ({
  x, y, name
}) => {
  return (
    <text x={x} y={y} fill="black" textAnchor="end" dominantBaseline="central">
      {name}
    </text>
  );
};

const SimplePieChart = React.createClass({
    render () {
    return (
        <ResponsiveContainer>
        <PieChart>
          <Pie data={data} fill="#8884d8" label={renderCustomizedLabel} nameKey="name"/>
        </PieChart>
       </ResponsiveContainer>
    );
  }
})

ReactDOM.render(
  <SimplePieChart />,
  document.getElementById('container')
);
Keilath
  • 436
  • 4
  • 10
  • why aren't you using the recharts Label method? – Mel May 15 '19 at 01:09
  • First of all, capital case `Label` is a component and not a method. The main reason is that Rechart's Label component is very poor regarding flexibility, and whenever you need a little bit more customization, you always end up writing your own custom label. – Keilath May 20 '19 at 22:54
  • Ok - but how do you use the Label from Rechart. It might not be very poor for my use case. I'm trying to keep to the documents as much as I can when I use these tools. – Mel May 21 '19 at 02:18
0

You can find a example for PieChartWithCustomizedLabel in http://recharts.org/en-US/examples/PieChartWithCustomizedLabel

or below code will help you

import React, { PureComponent } from 'react';
import {
  PieChart, Pie, Sector, Cell,
} from 'recharts';

const data = [
  { name: 'Group A', value: 400 },
  { name: 'Group B', value: 300 },
  { name: 'Group C', value: 300 },
  { name: 'Group D', value: 200 },
];

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

const RADIAN = Math.PI / 180;
const renderCustomizedLabel = ({
  cx, cy, midAngle, innerRadius, outerRadius, percent, index,
}) => {
   const radius = innerRadius + (outerRadius - innerRadius) * 0.5;
  const x = cx + radius * Math.cos(-midAngle * RADIAN);
  const y = cy + radius * Math.sin(-midAngle * RADIAN);

  return (
    <text x={x} y={y} fill="white" textAnchor={x > cx ? 'start' : 'end'} dominantBaseline="central">
      {`${(percent * 100).toFixed(0)}%`}
    </text>
  );
};

export default class Example extends PureComponent {
  static jsfiddleUrl = 'https://jsfiddle.net/alidingling/c9pL8k61/';

  render() {
    return (
      <PieChart width={400} height={400}>
        <Pie
          data={data}
          cx={200}
          cy={200}
          labelLine={false}
          label={renderCustomizedLabel}
          outerRadius={80}
          fill="#8884d8"
          dataKey="value"
        >
          {
            data.map((entry, index) => <Cell key={`cell-${index}`} fill={COLORS[index % COLORS.length]} />)
          }
        </Pie>
      </PieChart>
    );
  }
}

Demo here - link

  • hi - no - this doesn't work to solve the problem i raised n the question. I've posted an answer that does work - to help others learn – Mel May 22 '19 at 07:43
  • your sending label={renderLabel} - renderLabel is function which return value for every object in array. const data = [ { name: 'Group A', value: 400 }, { name: 'Group B', value: 300 }, { name: 'Group C', value: 300 }, { name: 'Group D', value: 200 }, ]; the return value will be label Same as you mention in your answer – Waseem Raja Shaik May 22 '19 at 07:57
  • @WaseemRajaShaik is it possible to have the pie chart line label on a scatter chart with rechart? i have an open question would be great if you could help – Trentfrompunchbowl1 Dec 09 '20 at 05:09