Custom legend labels in my rechart chart

Oliver Watkins picture Oliver Watkins · Jun 7, 2017 · Viewed 22.4k times · Source

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.

Answer

JonT picture JonT · Aug 18, 2017

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.