【问题标题】:ApexCharts barchart vertical categories logic in ReactJs?ReactJs中的ApexCharts条形图垂直类别逻辑?
【发布时间】:2019-05-24 17:53:13
【问题描述】:

我在试图弄清楚如何将正确的数据显示到正确的类别时遇到问题。 我的数据是来自 json API 的这种格式:

{
  "name" : "product1",
  "records": "5",
  "month" : "Jan",
},
{
  "name" : "product1",
  "records": "10",
  "month" : "Feb",
},
{
  "name" : "product1",
  "records": "20",
  "month" : "March",
},
{
  "name" : "product2",
  "records": "5",
  "month" : "Feb",
}

数据模型示例。

this.state = {
  barChart: { 
   options: {
      plotOptions: {
        xaxis: {
          categories: []
       }}}
        series: [{name: [], data: []}}

这是来自 apexcharts 的 ReactJs 中的状态 我已经花了几天时间,我试图根据字母对其进行排序:数据在图表中显示错误。 我正在阅读文档,但不知道该怎么做,或者如何让逻辑正确。类别不能如此重复:[Jan, Feb, March] 并且数据[记录]在它自己的类别中必须是正确的。

【问题讨论】:

  • 那么你的x轴和y轴的类别是什么?您是否正在尝试创建时间序列?
  • 我的 x 轴的类别是月份名称,y 轴是系列:[数据] 记录数。是的,我是,图表的逻辑来自基本条形图[apexcharts]
  • 知道了,那么您是否正在考虑创建类似堆叠条形图或折线图的东西,其中每条线都是自己的产品?看起来您需要的不仅仅是一个系列的对象。
  • @ChristopherNgo 只是一个基本的,一个堆叠的条形图,像这样:apexcharts.com/react-chart-demos/column-charts/basic,我确实有不止一个系列的对象.. 从 json 模型中可以看出,有两个产品,但其中一个有 [jan,feb,march] 的数据,而其他的只有 [feb] 的数据。
  • @ChristopherNgo 感谢,谢谢

标签: javascript reactjs apex apexcharts


【解决方案1】:

以下代码将为每个产品创建一个系列对象。每个产品都有自己的数据数组。其中每个数字依次对应一个月。为该产品的数据集中未使用的月份添加了一个 0 值。

示例数据集:

let data = [{
  "name" : "product1",
  "records": "5",
  "month" : "Jan",
},
{
  "name" : "product1",
  "records": "10",
  "month" : "Feb",
},
{
  "name" : "product1",
  "records": "20",
  "month" : "Mar",
},
{
  "name" : "product2",
  "records": "5",
  "month" : "Feb",
},
{
  "name" : "product1",
  "records": "5",
  "month" : "May",
},
{
  "name" : "product2",
  "records": "5",
  "month" : "Jun",
}
]

这将创建一个在数据集中使用的月份数组。没有重复。我们将使用它来映射每个产品在其特定月份的相应数据值。

创建类别:

let months = data.map((item) => item.month).filter((item, index, array) => array.indexOf(item) == index)

创作系列:

const productTotals = data.reduce((obj, curr) => {
    if(!obj[curr.name]){
        obj[curr.name] = []
    }

    obj[curr.name][months.indexOf(curr.month)] = parseInt(curr.records)
    return obj
}, {})

const series = Object.entries(productTotals).map(([name, prodArr]) => {
    return {
        name: name,
        data: months.map((month, monthIndex) => {
            if(!prodArr[monthIndex]){
                return 0
            } else {
                return prodArr[monthIndex]
            }

        })
    }

})

然后只需使用新的系列数据和类别更新属性即可。

this.state = {
  barChart: { 
   options: {
      plotOptions: {
        xaxis: {
          categories: [...months]
       }}}
        series: [...series]}

【讨论】:

  • 你是个传奇,工作得很好。以后有什么问题会告诉你的。
  • @Michael 谢谢 :)!这是一个很大的问题,所以我很乐意提供帮助!
  • 嗨@Christopher,仍在使用图表、数据网格进行项目,我正在尝试解决一个问题.. 联系您询问几个问题的最佳方式是什么?跨度>
  • 嗨@Michael,这人真棒,我希望这个项目进展顺利。如果您愿意,可以通过电子邮件与我联系:ChristopherNgo94@gmail.com 向我提出您的问题,我会看看是否可以提供帮助 :)
  • 嗨@Christopher,我通过电子邮件向您发送了一个问题。谢谢
猜你喜欢
  • 2012-04-16
  • 2016-10-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-28
  • 2015-05-29
  • 2013-12-07
  • 2020-05-28
相关资源
最近更新 更多