Custom legend labels in my rechart chart

I have a pretty simple 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 a chart showing different colors for "series1", "series2" and "series3".

Of course, I could set the actual values ​​I want to use for my legend in JSON, but that just doesn't look right. For example:

{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 the level of my series to a descriptive label.

I looked at the content in Legend: http://recharts.org/#/en-US/api/Legend , but this is more about completely rewriting the Legend component.

+10


source to share


2 answers


In yours Line

, Bar

and Area

add an attribute name

.

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 it up automatically:

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

By default, legend content is generated by line name, panel name, area, etc. If no name is given, dataKey will be used to alternatively create legend content.

+10


source


If you want this to work with <Pie/>

you can override payload

<Legend/>

. Please see the following example;

<Legend
  payload={
    data.map(
      item => ({
        id: item.name,
        type: "square",
        value: '${item.name} (${item.value}%)',
      })
    )
  }
/>

      



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

0


source







All Articles