如何使用 React-Chartkick 为 Chart.js BarCharts 设置附加选项

How to set additional options for Chart.js BarCharts using React-Chartkick

我正在尝试使用 React-Chartkick 和 Chart.js 显示条形图,我想自定义条形图的颜色。目前,我可以通过传递这样的道具将所有条形图设置为相同的颜色:<BarChart colours={["#fff"]} />.

在 React-Chartkick 中使用 LineCharts,您可以通过该道具传递一组颜色来设置线条的颜色。然而,BarCharts 似乎只接受第一种颜色。这是 React-Chartkick 的限制,还是我做错了什么?

我尝试通过 library 道具传递选项(如此处所述:https://www.chartjs.org/docs/latest/charts/bar.html#styling),因为这就是我自定义轴和标签颜色的方式,但这并没有t好像影响吧。

这是我当前的代码:

    state = {
        chartLibraryOptions: {
            borderColor: "#e34402", // does nothing here
            backgroundColor: "#e34402", // nor this
            scales: {
                yAxes: [
                    {
                        ticks: { fontColor: "#fff", autoSkip: false }
                    }
                ],
                xAxes: [
                    {
                        ticks: { fontColor: "#fff" }
                    }
                ]
            }
        }
    };

    render() {
        return (
            <BarChart
                data={this.state.chartData}
                library={this.state.chartLibraryOptions}
                colors={["#e34402", "#e3b502"]} // All bars are the first colour
            />
        );
    }

我希望能够更改每个条形的颜色,但毕竟我不确定这是否可以通过 Chartkick 实现?

好吧,我在一个项目中使用了相同的节点包,但采用不同的方法对我来说有点工作。几乎所有图表都具有相同的属性。

基本上,这个属性dataset={{ backgroundColor: ['white', 'yellow' ], }} 您需要为每个 bar 着色。您可以将字符串或字符串数​​组传递给 backgroundColor。

dataset中的backgroundColor取两种数据StringArray(object)。传递数据的典型示例如下。

  1. 当您将 backgroundColor 设置为字符串时,它会将相同的颜色应用于每个条形。例如 backgroundColor: 'red'

BarChart - <BarChart dataset={{ backgroundColor: 'red', }} />

  1. 当您将 backgroundColor 设置为数组时,它会将数组中的每种颜色应用于每个条形。例如 backgroundColor: ['red', 'yellow'],然后根据数据长度创建一个颜色循环。

column chart - <ColumnChart dataset={{ backgroundColor: ['red', 'yellow' ], }} />

下面的 React 实现:

/* eslint-disable no-plusplus */
 import React from 'react';
 import { ColumnChart, BarChart } from 'react-chartkick';
 import { chartOne } from '../common/chartData';
 import 'chart.js';

 const MonthlyGrowth = () => {
    const handleBgColors = () => {
       const firstColor = "#A00B16", secondColor = "#FAA226";
       const arrOfBgColors = [];
       for (let i = 1; i <= chartOne.length; i++) {
           if (i % 2 === 0) {
              arrOfBgColors.push(secondColor)
           } else {arrOfBgColors.push(firstColor)}
       }
       return arrOfBgColors;
   }

   return (
     <div className="bukka-card uk-card-default bg-white pt-4 pb-2 mr-1 pl-3 pr-2 pl- 
       lg-5">
        <h2 className="mt-2">4,500,000</h2>
        <BarChart
           dataset={{ borderWidth: 0, width: 0, backgroundColor: handleBgColors(), }}
           data={chartOne}
        />
      </div>
    )
}

export default MonthlyGrowth;