Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rechart - adding labels to charts

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?

like image 731
Mel Avatar asked May 12 '19 22:05

Mel


2 Answers

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>
like image 81
Mel Avatar answered Oct 17 '22 05:10

Mel


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')
);
like image 39
Keilath Avatar answered Oct 17 '22 05:10

Keilath