【问题标题】:React + D3: Rendering a bar chart from data in arrayReact + D3:从数组中的数据呈现条形图
【发布时间】:2018-08-19 08:34:07
【问题描述】:

我很难用 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 不是函数

【问题讨论】:

    标签: javascript reactjs d3.js


    【解决方案1】:

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

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

    【讨论】:

    • data = d3.range( ... ); 可能是另一种选择。
    • @vijayst,谢谢,这是有道理的,但现在我收到了这个错误:_d3Scale.scaleBand.domain is not a function
    • 是scaleBand().domain()
    猜你喜欢
    • 2016-08-29
    • 1970-01-01
    • 2021-10-28
    • 2016-12-03
    • 2021-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    相关资源
    最近更新 更多