I'm having difficulty rendering a bar chart with d3 (v4) and react.
I'm getting this error
data.map is not a function
data is stored in an array formatted as such:
{
Number:["2", "4", "8"]
Species:["cat", "dog", "rabbit"]
}
Which is passed into BarChart component as a prop:
<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;
EDIT:
If I change the format of the object to :
data = [
{
Number: '2',
Species: 'Cat'
},
{
Number: '4',
Species: 'Dog'
},
{
Number: '8',
Species: 'Rabbit'
}];
I get this error:
_d3Scale.scaleBand.domain is not a function
data seems to be an object and not an array. for the code to work, data should be:
data = [
{
Number: '2',
Species: 'Cat'
},
{
Number: '4',
Species: 'Dog'
},
{
Number: '8',
Species: 'Rabbit'
}];
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.