React Recharts - получение данных из разных объектов

Я использую React Recharts для визуализации, однако у меня возникла проблема с отображением простой гистограммы с различным соответствующим содержимым объекта.

[
  {
    "month": "2017-07",
    "commodities": [
      { "name": "wheat", "moves": 100, "avg_weight": 167 },
      { "name": "maize", "moves": 150, "avg_weight": 367 },
      { "name": "grains", "moves": 89, "avg_weight": 467 }
    ]
  },
  {
    "month": "2017-08",
    "commodities": [
      { "name": "mangoes", "moves": 140, "avg_weight": 167 },
      { "name": "grains", "moves": 190, "avg_weight": 47 }
    ]
  },
  {
    "month": "2017-09",
    "commodities": [
      { "name": "wheat", "moves": 130, "avg_weight": 267 },
      { "name": "tomatoes", "moves": 176, "avg_weight": 132 },
      { "name": "onions", "moves": 120, "avg_weight": 47 }
    ]
  },
  {
    "month": "2018-10",
    "commodities": [
      { "name": "oranges", "moves": 130, "avg_weight": 267 },
    ]
  },
]

У меня есть этот образец json-объекта, я хотел бы, чтобы месяц, когда мои XAxis и товары перемещались, были моими YAxs. В идеале изображение ниже представляет, как я хочу отображать свои данные. Спасибо вам за вашу помощь,. введите здесь описание изображения


person Erick Mwazonga    schedule 24.12.2018    source источник
comment
Выложите, пожалуйста, что пробовали?   -  person Harish Soni    schedule 24.12.2018
comment
Вот пример с сайта Recharts. jsfiddle.net/alidingling/30763kr7 Вы также можете использовать свойство tickFormatter для изменения формата времени оси x   -  person Dusty    schedule 24.12.2018


Ответы (1)


Есть три шага, чтобы получить то, что вы ищете:

  1. Преобразуйте данные в формат Rechart require
  2. Получите уникальные этикетки

Вот рабочая песочница кода https://codesandbox.io/s/n95n2wpp6l

import React, { Component } from "react";
import {
  BarChart,
  Bar,
  XAxis,
  YAxis,
  CartesianGrid,
  Tooltip,
  Legend
} from "recharts";
import _ from "underscore";

class BarGraph extends Component {
  state = {
    converted: [],
    labels: []
  };
  componentDidMount() {
    let data = [
      {
        month: "2017-07",
        commodities: [
          { name: "wheat", moves: 100, avg_weight: 167 },
          { name: "maize", moves: 150, avg_weight: 367 },
          { name: "grains", moves: 89, avg_weight: 467 }
        ]
      },
      {
        month: "2017-08",
        commodities: [
          { name: "mangoes", moves: 140, avg_weight: 167 },
          { name: "grains", moves: 190, avg_weight: 47 }
        ]
      },
      {
        month: "2017-09",
        commodities: [
          { name: "wheat", moves: 130, avg_weight: 267 },
          { name: "tomatoes", moves: 176, avg_weight: 132 },
          { name: "onions", moves: 120, avg_weight: 47 }
        ]
      },
      {
        month: "2018-10",
        commodities: [{ name: "oranges", moves: 130, avg_weight: 267 }]
      }
    ];
    let converted = this.convertData(data);
    let labels = this.getLabels(data);
    console.log(labels, converted);

    this.setState({
      converted: converted,
      labels: labels
    });
  }

  convertData(data) {
    let arr = [];
    for (let i = 0; i < data.length; i++) {
      let obj = { month: data[i].month };
      // loop throgh comodities
      for (let j = 0; j < data[i].commodities.length; j++) {
        let commodity = data[i].commodities[j];
        obj[commodity.name] = commodity.moves;
      }
      arr.push(obj);
    }
    return arr;
  }

  getLabels(data) {
    let arr = [];
    _.each(data, obj => {
      arr = arr.concat(obj.commodities);
    });
    let grouped = _.groupBy(arr, "name");
    return Object.keys(grouped);
    //return Object.keys(_.groupby(arr.name));
  }

  render() {
    return (
      <BarChart
        width={600}
        height={300}
        data={this.state.converted}
        margin={{ top: 5, right: 30, left: 20, bottom: 5 }}
      >
        <CartesianGrid strokeDasharray="3 3" />
        <XAxis dataKey="month" />
        <YAxis />
        <Tooltip />
        <Legend />
        {this.state.labels.map((label, index) => (
          <Bar key={index} dataKey={label} fill="#8884d8" />
        ))}
      </BarChart>
    );
  }
}

export default BarGraph;

person Aamin Khan    schedule 24.12.2018
comment
Прежде всего, спасибо за вашу помощь. Однако можно ли убрать отображение «нулевой полосы», когда метка находится не в текущем месяце? - person Erick Mwazonga; 03.01.2019