【问题标题】:Custom legend labels in my rechart chart我的图表图表中的自定义图例标签
【发布时间】:2017-06-07 12:51:28
【问题描述】:

我的 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}

我想在我的 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}

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

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

【问题讨论】:

  • 你找到解决办法了吗?

标签: recharts


【解决方案1】:

在您的LineBarArea 中添加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" />

图例会自动选择这个:

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

默认情况下,legend 的内容是由 Line 的名字生成的, Bar,Area等。当没有设置名称时,dataKey将用于 交替生成图例内容。

【讨论】:

  • 饼图呢?
【解决方案2】:

如果您希望在 &lt;Pie /&gt; 上使用此功能,您可以覆盖 &lt;Legend /&gt; payload。请看下面的例子;

<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

【讨论】:

  • 它很有用,但它似乎破坏了图例项目中的颜色
【解决方案3】:

对于自定义图例,使用内容道具,参考: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} />

【讨论】:

  • OP 明确引用了 content 选项并拒绝了它。
猜你喜欢
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-10
  • 1970-01-01
相关资源
最近更新 更多