【问题标题】:Get json data from api and map in barchart reactjs从 api 获取 json 数据并在 barchart reactjs 中映射
【发布时间】:2020-05-14 06:09:25
【问题描述】:

我想通过从 API 中的 JSON 文件获取数据来显示如下图所示的条形图。我是 reactjs 的初学者,我尝试过并形成了下图。 My created Image

我想通过从 API 获取数据来显示这样的条形图。

The real graph

我试过这段代码:

import React from "react";
import Chart from "react-apexcharts";
import axios from "axios";

const colors = ["#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0"];
class SalesPerSegment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: {
        plotOptions: {
          bar: {
            horizontal: false,
            endingShape: "rounded",
            columnWidth: "55%",
          },
        },
        dataLabels: {
          enabled: false,
        },
        stroke: {
          show: true,
          width: 2,
          colors: ["transparent"],
        },
        xaxis: {
          categories: ["Q1", "Q2", "Q3", "Q4"],
        },
        yaxis: {
          title: {
            text: "$ (thousands)",
          },
        },
        fill: {
          opacity: 1,
        },
        tooltip: {
          y: {
            formatter: function (val) {
              return "$ " + val + " thousands";
            },
          },
        },
        legend: {
          offsetY: -10,
        },
      },
      series: [
        {
          name: "Big Spenders",
          data: [44, 55, 57, 56],
        },
        {
          name: "Registered",
          data: [76, 85, 101, 98],
        },
        {
          name: "VIP Shoppers",
          data: [56, 35, 45, 20],
        },
        {
          name: "Coupon Lovers",
          data: [100, 60, 45, 34],
        },
        {
          name: "Guest",
          data: [43, 20, 80, 90],
        },
      ],
    };
  }
  componentDidMount() {
    var token = localStorage.getItem("auth");
    axios
      .get("http://202.143.121.156:3031/quarterly_cluster_sales", {
        headers: { Authorization: "Bearer " + token },
      })
      .then((response) => {
        if (response.status === 200 && response != null) {
          console.log(response.data);
          let my_series = [
            {
              data: [],
            },
          ];

          response.data.forEach((item) => {
            my_series[0].data.push(item.value);
          });
          //   console.log(my_series);
          this.setState({
            series: my_series,
            // options: my_options,
          });
        } else {
          console.log("problem");
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }
  render() {
    return (
      <div id="chart" className="apexcharts-content">
        <Chart
          options={this.state.options}
          series={this.state.series}
          type="bar"
          height={350}
        />
      </div>
    );
  }
}

export default SalesPerSegment;
API: http://202.143.121.156:3031/quarterly_cluster_sales

API 中的 JSON 文件:

[
    {
        "quarter": 1,
        "cluster_id": 0,
        "value": 2057227.0900000404,
        "details": [
            {
                "name": "Best Customers",
                "rfm": "111",
                "description": "Bought most recently and most often, and spend the most",
                "action": "No price incentives, new products, and loyalty programs"
            }
        ]
    },
    {
        "quarter": 1,
        "cluster_id": 1,
        "value": 608225.1699999988,
        "details": [
            {
                "name": "Loyal Customers",
                "rfm": "X1X",
                "description": "Buy most frequently",
                "action": "Use R and M to further segment"
            }
        ]
    },
    {
        "quarter": 1,
        "cluster_id": 2,
        "value": 675745.5300000027,
        "details": [
            {
                "name": "Big Spenders",
                "rfm": "XX1",
                "description": "Spend the most",
                "action": "Market your most expensive products"
            }
        ]
    },
    {
        "quarter": 1,
        "cluster_id": 3,
        "value": 11000.01,
        "details": [
            {
                "name": "Almost Lost",
                "rfm": "311",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 1,
        "cluster_id": 4,
        "value": 612694.9899999996,
        "details": [
            {
                "name": "Lost Customers",
                "rfm": "411",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 2,
        "cluster_id": 1,
        "value": 2619889.249999953,
        "details": [
            {
                "name": "Loyal Customers",
                "rfm": "X1X",
                "description": "Buy most frequently",
                "action": "Use R and M to further segment"
            }
        ]
    },
    {
        "quarter": 2,
        "cluster_id": 2,
        "value": 1167647.2600000023,
        "details": [
            {
                "name": "Big Spenders",
                "rfm": "XX1",
                "description": "Spend the most",
                "action": "Market your most expensive products"
            }
        ]
    },
    {
        "quarter": 2,
        "cluster_id": 3,
        "value": 13384.419999999987,
        "details": [
            {
                "name": "Almost Lost",
                "rfm": "311",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 2,
        "cluster_id": 4,
        "value": 929743.69,
        "details": [
            {
                "name": "Lost Customers",
                "rfm": "411",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 3,
        "cluster_id": 0,
        "value": 425981.5300000015,
        "details": [
            {
                "name": "Best Customers",
                "rfm": "111",
                "description": "Bought most recently and most often, and spend the most",
                "action": "No price incentives, new products, and loyalty programs"
            }
        ]
    },
    {
        "quarter": 3,
        "cluster_id": 1,
        "value": 1663863.2799999884,
        "details": [
            {
                "name": "Loyal Customers",
                "rfm": "X1X",
                "description": "Buy most frequently",
                "action": "Use R and M to further segment"
            }
        ]
    },
    {
        "quarter": 3,
        "cluster_id": 2,
        "value": 1138108.8700000008,
        "details": [
            {
                "name": "Big Spenders",
                "rfm": "XX1",
                "description": "Spend the most",
                "action": "Market your most expensive products"
            }
        ]
    },
    {
        "quarter": 3,
        "cluster_id": 3,
        "value": 11125.619999999992,
        "details": [
            {
                "name": "Almost Lost",
                "rfm": "311",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 3,
        "cluster_id": 4,
        "value": 679263.6300000001,
        "details": [
            {
                "name": "Lost Customers",
                "rfm": "411",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 4,
        "cluster_id": 0,
        "value": 2253072.7500000177,
        "details": [
            {
                "name": "Best Customers",
                "rfm": "111",
                "description": "Bought most recently and most often, and spend the most",
                "action": "No price incentives, new products, and loyalty programs"
            }
        ]
    },
    {
        "quarter": 4,
        "cluster_id": 2,
        "value": 42846.10999999999,
        "details": [
            {
                "name": "Big Spenders",
                "rfm": "XX1",
                "description": "Spend the most",
                "action": "Market your most expensive products"
            }
        ]
    },
    {
        "quarter": 4,
        "cluster_id": 3,
        "value": 3720.229999999999,
        "details": [
            {
                "name": "Almost Lost",
                "rfm": "311",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    },
    {
        "quarter": 4,
        "cluster_id": 4,
        "value": 506143.4200000002,
        "details": [
            {
                "name": "Lost Customers",
                "rfm": "411",
                "description": "Haven't purchased for some time, but purchased frequently and spend the most",
                "action": "Aggressive price incentives"
            }
        ]
    }
]

JSON 文件有 4 个季度。每个季度有 5 个集群。我需要从 JSON 中获取数据,并在图表中使用不同颜色映射每个季度集群,如上图所示。如果您需要其他东西,请在下方评论,我会提供。

【问题讨论】:

  • 我没有看到您将颜色传递给图表。我认为所有这些空间和对齐都需要从图形选项中格式化。您使用的图表是什么?
  • 我正在使用条形图。颜色由代码定义。

标签: json reactjs api rest


【解决方案1】:
import React from "react";
import Chart from "react-apexcharts";
import axios from "axios";
import { uniq } from 'lodash';

const colors = ["#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0"];
class SalesPerSegment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: {
        plotOptions: {
          bar: {
            horizontal: false,
            endingShape: "rounded",
            columnWidth: "55%",
          },
        },
        dataLabels: {
          enabled: false,
        },
        stroke: {
          show: true,
          width: 2,
          colors: ["transparent"],
        },
        xaxis: {
          categories: ["Q1", "Q2", "Q3", "Q4"],
        },
        yaxis: {
          title: {
            text: "$ (thousands)",
          },
        },
        fill: {
          opacity: 1,
        },
        tooltip: {
          y: {
            formatter: function (val) {
              return "$ " + val + " thousands";
            },
          },
        },
        legend: {
          offsetY: -10,
        },
        series: []
      },
    };
  }

  componentDidMount() {
    var token = localStorage.getItem("auth");
    axios
      .get("http://202.143.121.156:3031/quarterly_cluster_sales", {
        headers: { Authorization: "Bearer " + token },
      })
      .then((response) => {
        if (response.status === 200 && response != null) {
          const allClusterId = response.data.map(d => d.cluster_id);
          const uniqClusterIds = uniq(allClusterId);
          const series = uniqClusterIds.map(clusterId => {
            const dataFilter = myData.filter(d => d.cluster_id === clusterId);
            const data = dataFilter.map(d => d.value);
            return {
              name: clusterId,
              data
            }
          });
          this.setState({
            options: {
              ...this.state.options,
              colors,
              series
            }
          })
        } else {
          console.log("problem");
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }
  render() {
    return (
      <div id="chart" className="apexcharts-content">
        <Chart
          options={this.state.options}
          series={this.state.series}
          type="bar"
          height={350}
        />
      </div>
    );
  }
}

export default SalesPerSegment;

【讨论】:

  • 第 82 行:'myData' 未定义 no-undef 第 85 行:'myData' 未定义 no-undef
  • 将 myData 更改为 response.data
  • 它采用硬编码值。我需要上面给出的 json 文件中的数据。
  • 我使用您的 json 文件中的响应数据编辑了代码。你可以再检查一遍
【解决方案2】:

Diamond95 帮助我解决了问题。该解决方案略有修改(工作代码)

import React from "react";
import Chart from "react-apexcharts";
import axios from "axios";
import { uniq } from "lodash";
const colors = ["#008FFB", "#00E396", "#FEB019", "#FF4560", "#775DD0"];
class SalesPerSegment extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      options: {
        plotOptions: {
          bar: {
            horizontal: false,
            endingShape: "rounded",
            columnWidth: "55%",
          },
        },
        dataLabels: {
          enabled: false,
        },
        stroke: {
          show: true,
          width: 2,
          colors: ["transparent"],
        },
        xaxis: {
          categories: ["Q1", "Q2", "Q3", "Q4"],
        },
        yaxis: {
          title: {
            text: "$ (thousands)",
          },
        },
        fill: {
          opacity: 1,
        },
        tooltip: {
          y: {
            formatter: function (val) {
              return "$ " + val + " thousands";
            },
          },
        },
        legend: {
          offsetY: -10,
        },
      },
      series: [
        {
          name: "Best Customers",
          data: [],
        },
        {
          name: "Loyal Customers",
          data: [],
        },
        {
          name: "Big Spenders",
          data: [],
        },
        {
          name: "Almost Lost",
          data: [],
        },
        {
          name: "Lost Customers",
          data: [],
        },
      ],
    };
  }
  componentDidMount() {
    var token = localStorage.getItem("auth");
    axios
      .get("http://202.143.121.156:3031/quarterly_cluster_sales", {
        headers: { Authorization: "Bearer " + token },
      })
      .then((response) => {
        if (response.status === 200 && response != null) {
          // console.log(response.data);

          const allClusterId = response.data.map((d) => d.cluster_id);
          const uniqClusterIds = uniq(allClusterId);
          const series = uniqClusterIds.map((clusterId) => {
            const dataFilter = response.data.filter(
              (d) => d.cluster_id === clusterId
            );
            const data = dataFilter.map((d) => Math.floor(d.value));

            let clusterNames;
            dataFilter
              .map((d) => d.details)
              .forEach((item) => {
                // console.log(item[0].name);
                clusterNames = item[0].name;
              });

            return {
              name: clusterNames,
              data,
            };
          });
          // console.log(series, "series values");
          this.setState({
            ...this.state.options,
            colors,
            series,
          });
        } else {
          console.log("problem");
        }
      })
      .catch((error) => {
        console.log(error);
      });
  }
  render() {
    // console.log(this.state.series);
    return (
      <div id="chart" className="apexcharts-content">
        {this.state.series.length && (
          <>
            <Chart
              options={this.state.options}
              series={this.state.series}
              type="bar"
              height={350}
            />
          </>
        )}
      </div>
    );
  }
}

export default SalesPerSegment;

【讨论】:

    猜你喜欢
    • 2022-01-18
    • 1970-01-01
    • 2021-05-22
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-07
    • 1970-01-01
    相关资源
    最近更新 更多