ReactJs中的ApexCharts条形图垂直类别逻辑? [英] ApexCharts barchart vertical categories logic in ReactJs?
问题描述
我在试图弄清楚如何将正确的数据显示到正确的类别时遇到了问题.我的数据是来自 json API 的这种格式:
I am having a problem trying to figure out how to display the correct data to the correct category. My data is in this format from a 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中的状态我已经花了几天的时间,我试图根据字母表对其进行排序:图表中显示的数据是错误的.我正在阅读文档,但不知道该怎么做,或者如何使逻辑正确.类别不能重复:[一月、二月、三月]并且数据[记录]在它自己的类别中必须是正确的.
This is the state in ReactJs from apexcharts I've been spending couple of days and I've tried to sort it based on alphabet: which the data was wrong displayed in the graph. I was reading the documentation but didn't figure out how to do, or how to get the logic right. the categories cannot repeat so: [Jan, Feb, March] and the data[records] has to be correct in it's own category.
推荐答案
以下代码将为每个产品创建一个系列对象.每个产品都有自己的数据数组.其中每个数字依次对应一个月.在该产品的数据集中未使用的一个月内添加 0 值.
The following code will create a series object for each Product. Each Product will have its own data array. Where each number corresponds sequentially to a month. A 0 value is added in place for a month that was not utilized in the data-set for that product.
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",
}
]
这将创建数据集中使用的月份数组.没有重复.我们将使用它来映射每个产品在特定月份的相应数据值.
This creates an array of months that were used in the data-set. No duplicates. We will use it to map the corresponding data-values of each product in their specific month.
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]
}
})
}
})
然后只需使用您的新系列数据和类别更新属性.
Then simply update the properties with your new series data and categories.
this.state = {
barChart: {
options: {
plotOptions: {
xaxis: {
categories: [...months]
}}}
series: [...series]}
这篇关于ReactJs中的ApexCharts条形图垂直类别逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!