【问题标题】:How do I change the color of each bar in Recharts?如何更改 Recharts 中每个条的颜色?
【发布时间】:2021-04-14 14:17:44
【问题描述】:

我的一个 React 页面上有一个条形图。它从另一个页面传递的道具中获取数据。我有一个条形图,显示三个不同的数据。一个显示“正确”,另一个显示“不正确”,最后一个显示“总”。我想让每个条的颜色不同。我尝试过使用 Cell 功能,但无法正常工作。我还尝试更改每条数据的名称,但没有运气。不幸的是,Recharts 的文档并不多。有人有什么想法吗?

import React from 'react';
import {
    ResponsiveContainer, BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid, Tooltip, Legend,
} from 'recharts';

export default class GameChart extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            axes: [
                { primary: true, type: 'ordinal', position: 'left' },
                { position: 'bottom', type: 'linear', stacked: true }
            ],
            series: {
                type: 'bar'
            },
            chartData: [
                {
                    name: 'Correct',
                    total: 0,
                },
                {
                    name: 'Incorrect',
                    total: 0,
                },
                {
                    name: 'Total',
                    total: 0,
                },
            ],
            chartLayout: {
                title: 'Math Game Results',
                yaxis: {
                    showticklabels: false
                },
            }
        }
    }

    componentDidUpdate(prevProps) {
        if (prevProps.chartData.totalCounter !== this.state.chartData[2].total) {
            let tempState = this.state;
            tempState.chartData = [
                {
                    name: 'Correct',
                    total: this.props.chartData.correctCounter,
                },
                {
                    name: 'Incorrect',
                    total: this.props.chartData.incorrectCounter,
                },
                {
                    name: 'Total',
                    total: this.props.chartData.totalCounter,
                },
            ];
            this.setState(tempState);
        }
    }

    render () {
        return (
            <div>
                {
                    (this.state.chartData[2].total > 0) ?
                        (<ResponsiveContainer width="95%" height={225}>
                            <BarChart
                                data={this.state.chartData.slice()}
                                layout="vertical" barCategoryGap={5}
                                margin={{top: 5, right: 30, left: 20, bottom: 5,}}
                            >
                                <XAxis
                                    type="number"
                                    stroke="#000000"
                                />
                                <YAxis
                                    type="category"
                                    stroke="#000000"
                                    dataKey="name"
                                />
                                <Tooltip
                                    wrapperStyle={{ width: 100, backgroundColor: '#ccc' }}
                                    formatter={function(name) {return `${name}`}}
                                />
                                <Bar
                                    dataKey="total"
                                    fill="#00a0fc"
                                    stroke="#000000"
                                    strokeWidth={1}
                                />
                            </BarChart>
                        </ResponsiveContainer>
                        ):
                        (null)
                }
            </div>
        );
    }
}

这是当前设置的图片。如您所见,每个条具有相同的颜色。

【问题讨论】:

  • 这个example可以帮助你吗?这是关于条形的形状,但我认为在Bar 组件内部,您可以指定每个Cell 的填充颜色。
  • @c0m1t 我一直在看同一个例子。我认为这绝对是正确的道路,我只是不明白如何映射我的数据,因为它不像他们的列表。
  • 您是否尝试过将this.state.chartData.map((entry, index) =&gt; &lt;Cell fill={/* some dynamic fill based on entry or index */} /&gt; 作为Bar 组件的子组件?看到这个link
  • @c0m1t 我明白了!在发布此之前,我认为我的颜色列表位于错误的位置,因此 React 无法读取它。我会发布答案,感谢您的帮助!

标签: javascript reactjs graph state bar-chart


【解决方案1】:

好的,感谢@c0m1t 我让它工作了。我所要做的就是在状态类之上列出一个颜色列表!

import React from 'react';
import {
    BarChart, Bar, XAxis, Cell, YAxis, Tooltip, ResponsiveContainer,
} from 'recharts';

const barColors = ["#1f77b4", "#ff7f0e", "#2ca02c"]

export default class Example extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            chartData: [
                {
                    name: "Correct",
                    total: this.props.chartData.correctCounter
                },
                {
                    name: "Incorrect",
                    total: this.props.chartData.incorrectCounter
                },
                {
                    name: "Total",
                    total: this.props.chartData.totalCounter
                }
            ]
        }
    }

    render() {
        return (
            <ResponsiveContainer width="95%" height={450}>
                <BarChart
                    data={this.state.chartData.slice()}
                    margin={{ top: 20, right: 20, left: 20, bottom: 5, }}
                    data={this.state.chartData}
                >
                <XAxis
                    dataKey="name"
                    stroke="#000000"
                />
                <YAxis
                    stroke="#000000"
                />
                <Tooltip
                    wrapperStyle={{ width: 100, backgroundColor: '#ccc' }}
                    formatter={function(total) {return `${total}`}}
                />
                <Bar
                    dataKey="total"
                    fill="#00a0fc"
                    stroke="#000000"
                    strokeWidth={1}
                >
                    {
                        this.state.chartData.map((entry, index) => (
                            <Cell key={`cell-${index}`} fill={barColors[index % 20]} />
                        ))
                    }
                </Bar>
                </BarChart>
            </ResponsiveContainer>
        );
    }
}

现在每个条都有不同的颜色。

【讨论】:

  • 感谢您在找到答案后发布答案!一直很感激
  • 对于任何想知道fill={barColors[index % 20]} 的人来说,这个想法是您将barColors 创建为您喜欢的20 种颜色的数组(可能来自w3schools.com/colors/colors_palettes.asp),然后每个条获得下一种颜色,筋疲力尽时绕到第一个。
  • 嗨。如何为每个条设置不同的渐变颜色?我尝试在 map 函数中包含&lt;lineargradient&gt; 组件并根据索引设置stopcolor。但无法实现。好像我必须在&lt;Bar&gt; 组件之外定义lineargradient 组件
猜你喜欢
  • 2022-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-06
  • 1970-01-01
  • 2021-09-24
  • 2020-04-12
相关资源
最近更新 更多