我的rechart图表中的自定义图例标签

Oli*_*ins 11 recharts

我的recharts组件有一个非常直接的数据数组:

{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}
Run Code Online (Sandbox Code Playgroud)

我想在Legend中为系列值添加标签.而不是图表显示"series1","series2"和"series3"的不同颜色.

当然我可以在JSON中设置我想用于传说的实际值,但这看起来并不合适.例如:

{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}
Run Code Online (Sandbox Code Playgroud)

我需要将我的系列级别映射到描述性标签.

我查看了Legend 中的内容:http://recharts.org/#/en-US/api/Legend,但这似乎更关心完全重写Legend Component.

小智 17

在你的Line,BarArea添加一个name属性.

例:

<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" />
Run Code Online (Sandbox Code Playgroud)

图例会自动选择它:

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

默认情况下,图例的内容由Line,Bar,Area等名称生成.如果没有设置名称,dataKey将用于交替生成图例内容.

  • 饼图呢? (2认同)

ghg*_*hjk 8

如果您想让它在 a 上工作,<Pie />您可以覆盖<Legend /> payload. 请看下面的例子;

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

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