31

I have a pretty straight forward data array for my recharts component :

{name: '12.1.2011', series1: 4000, series2: 2400, series3: 2400},
{name: '12.2.2011', series1: 3000, series2: 1398, series3: 2210},
{name: '12.3.2011', series1: 2000, series2: 9800, series3: 2290}

I would like to have labels for the series values in my Legend. Instead of the chart showing me the different colors for "series1", "series2", and "series3".

Of course I could set the actual values I want to use for my legend in the JSON already but this just doesn't look right. Eg :

{name: '12.1.2011', 'My nice long descriptive text': 4000, 'Some other text': 2400, 'Some other descriptive text': 2400},
{name: '12.2.2011', 'My nice long descriptive text': 3000, 'Some other text': 1398, 'Some other descriptive text: 2210},
{name: '12.3.2011', 'My nice long descriptive text': 2000, 'Some other text': 9800, 'Some other descriptive text: 2290}

I need to map my series level to a descriptive label.

I have looked at content in Legend : http://recharts.org/#/en-US/api/Legend, but that seems more concerned with completely rewriting the Legend Component.

Oliver Watkins
  • 12,575
  • 33
  • 119
  • 225

3 Answers3

51

In your Line, Bar and Area add a name attribute.

Example:

<Line name="# Apples" type="monotone" dataKey="series1" stroke="#FF0000" />
<Line name="# Bananas" type="monotone" dataKey="series2" stroke="#FFFF00" />
<Line name="# Grapes" type="monotone" dataKey="series3" stroke="#FF00FF" />

The legend will pick this up automatically:

http://recharts.org/en-US/api/Legend

By default, the content of legend is generated by the name of Line, Bar, Area, etc. When no name has been setted, dataKey will be used to generate legend content alternatively.

abhirathore2006
  • 3,317
  • 1
  • 25
  • 29
JonT
  • 539
  • 4
  • 4
14

If you're looking to get this working on a <Pie /> you can override the <Legend /> payload. Please see the following example;

<Legend
  payload={
    data.map(
      (item, index) => ({
        id: item.name,
        type: "square",
        value: `${item.name} (${item.value}%)`,
        color: colors[index % colors.length]
      })
    )
  }
/>

http://recharts.org/en-US/api/Legend#payload

Angelo
  • 3
  • 3
ghghjk
  • 223
  • 4
  • 11
3

For custom legend, use content props, Ref: https://recharts.org/en-US/api/Legend#content

const renderLegend = (props) => {
  const { payload } = props;

  return (
    <ul>
      {
        payload.map((entry, index) => (
          <li key={`item-${index}`}>{entry.value}</li>
        ))
      }
    </ul>
  );
}
<Legend content={renderLegend} />
Somnath Kadam
  • 6,051
  • 6
  • 21
  • 37