简体   繁体   English

React + D3:从数组中的数据渲染条形图

[英]React + D3: Rendering a bar chart from data in array

I'm having difficulty rendering a bar chart with d3 (v4) and react. 我在用d3(v4)渲染条形图时有困难并做出反应。

I'm getting this error 我收到这个错误

data.map is not a function data.map不是函数

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组件中:

 <BarChart data={data} />

BarChart.jsx 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 _d3Scale.scaleBand.domain不是函数

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'
  }];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM