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

时间:2019-06-05 12:30:37

标签: javascript reactjs chart.js 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),因为这是我自定义轴和标签的颜色的方式,但这似乎没有影响酒吧。

这是我当前的代码:

    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是否可以做到这一点?

1 个答案:

答案 0 :(得分:0)

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

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

数据集中的backgroundColor接受两种类型的数据StringArray(object)。传递数据的典型示例如下。

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

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

bar chart one color]

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

列图表-<ColumnChart dataset={{ backgroundColor: ['red', 'yellow' ], }} />

enter image description here

在下面反应实施

/* 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 handleBgColor = () => {
       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: handleBgColor(), }}
           data={chartOne}
        />
      </div>
    )
}

export default MonthlyGrowth;