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;