我正在使用react-chartjs-2生成图表,并从我的API中提取“类别”。类别的数量是动态的(将在0到大约20之间,但最终取决于用户)。完全根据我的主主题颜色(#3B73B4)为甜甜圈图表的每个切片生成不同颜色的最佳方法是什么?最好只是做一个渐变?
我的图形组件如下:
import React, { Component } from 'react';
import { Doughnut } from 'react-chartjs-2';
import colors from '../_styles/colors';
class CurrentPackGraph extends Component {
constructor(props) {
super(props);
this.state = {
categories: props.data.categories,
}
}
render() {
const data = {
labels: this.state.categories.map(c => c.name),
datasets: [{
data : this.state.categories.map(i => i.items.length),
backgroundColor : [
colors.darkPrimary,
'#36A2EB',
'#FFCE56',
],
hoverBackgroundColor: [
colors.darkPrimary,
'#36A2EB',
'#FFCE56',
],
}],
};
const chartOptions = {
maintainAspectRatio: false,
};
return (
<Doughnut
data={data}
options={chartOptions}
height={300}
/>
);
}
}
export default CurrentPackGraph;
答案 0 :(得分:1)
您可以使用d3比例库来实现:
import * as scale from "d3-scale";
// Set amount of categories
const length = 20;
// Generate color scale
const colors = scale
.scaleLinear()
.domain([0, length])
.range(["#fff", "#3B73B4"]);
// define some inline styles for illustration
const getBoxStyle = color => ({
margin: "20px",
backgroundColor: `${color}`
});
然后我们仅使用生成的比例尺:
function App() {
const squares = [];
for (let i = 0; i < length; i++) {
squares.push(
<div style={getBoxStyle(colors(i))} key={i}>
{colors(i)} {i}
</div>
);
}
return <div className="App">{squares}</div>;
}
请在此处查看工作示例:https://codesandbox.io/s/p96vz6r5m0