我很难用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不是函数
答案 0 :(得分:0)
数据似乎是一个对象,而不是数组。为了使代码正常工作,数据应为:
data = [
{
Number: '2',
Species: 'Cat'
},
{
Number: '4',
Species: 'Dog'
},
{
Number: '8',
Species: 'Rabbit'
}];