首页 > 解决方案 > 如何在 Victory Pie 中指定数据对象内的色阶

问题描述

我曾经VictoryChart实现一个饼图,它工作得很好......

render() {

    const data_distribution = this.state.pie_keys.map((d) => ({x:d, y:this.state.pie_data[d], label:d }));

    return (
      <div className="App">
        <div className="pie_wrapper">
          <VictoryPie
            labelComponent={<VictoryTooltip cornerRadius={0} />}   
            padAngle={0.5}
            innerRadius={100}
            width={400} height={400}
            style={{ 
              labels: { fontSize: 15, fill: "black"},
              data: {
                  fillOpacity: 0.9, stroke: "white", strokeWidth: 3
              }
            }}
            labelRadius={90}
            data = {data_distribution}
          />
        </div>
      </div>
    );
  }

需要注意的是,它data_distribution看起来简单如下......

data={[
    { x: "Fac of Engineering & Appl Sci", y: 8.557902403495994 },
    { x: "Faculty of Arts and Science", y: 53.775188152464196 },
    { x: "Faculty of Education", y: 13.085700412721534 },
    ...
    ...
  ]}

所以我想知道我是否可以为数据对象中的每一块饼图设置颜色。该文档指定...

色阶:“灰度”、“定性”、“热图”、“暖色”、“冷色”、“红色”、“绿色”、“蓝色”。VictoryPie 将按索引为每个切片分配颜色,除非它们在数据对象中明确指定。

这说你可以,但我不知道怎么做。我尝试了以下...

data={[
    { x: "Fac of Engineering & Appl Sci", y: 8.557902403495994, colorScale:"red" },
    { x: "Faculty of Arts and Science", y: 53.775188152464196, colorScale:"red" },
    { x: "Faculty of Education", y: 13.085700412721534, colorScale:"red" },
    ...
    ...
]}

这转化为...

const data_distribution = this.state.pie_keys.map((d) => ({x:d, y:this.state.pie_data[d], label:d, colorScale:"red"}));

但是,它们不会变红。我在网上找不到示例。这可能吗?

我知道我可以定义colorScale: {[...]},但这不是我要问的。我希望能够从数据对象中设置饼图的每一块。

标签: reactjspie-chartvictory-charts

解决方案


我知道这个问题已经“回答”了,但答案让我不满意。由于我来到这里并感到沮丧,因此我决定发布我的解决方案,希望其他人可以从中受益。

style您可以使用道具 覆盖单个切片的颜色:

<VictoryPie
  data={[
    { x: "Cats", y: 35 },
    { x: "Dogs", y: 40 },
    { x: "Birds", y: 55 }
  ]}
  style={{
    data: {
      fill: ({ y }) =>
        y > 49 ? 'green'
        : y > 39 ? 'yellow'
        : 'tomato'
    }
  }}
/>

在这种情况下,您根本不应该使用colorScale。我已经阅读了源代码,据我所知,这是在VictoryPie.


推荐阅读