React + D3:从数组中的数据呈现条形图



我很难用 d3 (v4( 渲染条形图并做出反应。

我收到此错误

data.map 不是一个函数

数据存储在格式如下的数组中:

{
Number:["2", "4", "8"]
Species:["cat", "dog", "rabbit"]
}

它作为道具传递到BarChart组件中:

<BarChart data={data} />

BarChart.jsx

import React,{ Component } from 'react';
import { scaleBand, scaleLinear } from 'd3-scale';
class BarChart extends Component {
render() {
const svgWidth = 960, svgHeight = 500;
const margin = { top: 20, right: 20, bottom: 30, left: 40 },
width = svgWidth - margin.left - margin.right,
height = svgHeight - margin.top - margin.bottom;
const data = this.props.data;
const x = scaleBand.domain(data.map(d => d.Species))
.rangeRound([0, width])
.padding(0.1),
y = scaleLinear.domain([0, max(data, d => d.Number)])
.rangeRound([height, 0]);
<svg width={svgWidth} height={svgHeight}>
<g transform={`translate(${margin.left}, ${margin.top})`}>
{data.map(d => (
<rect
x={x(d.Species)}
y={y(d.Number)}
width={x.bandwidth()}
height={height - y(d.frequency)}
/>
))}
</g>
</svg>
}
};

export default BarChart;

编辑:

如果我将对象的格式更改为:

data = [
{
Number: '2',
Species: 'Cat'
},
{
Number: '4',
Species: 'Dog'
},
{
Number: '8',
Species: 'Rabbit'
}];

我收到此错误:

_d3Scale.scaleBand.domain不是一个函数

数据似乎是一个对象而不是数组。 要使代码正常工作,数据应为:

data = [
{
Number: '2',
Species: 'Cat'
},
{
Number: '4',
Species: 'Dog'
},
{
Number: '8',
Species: 'Rabbit'
}];

最新更新