最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Chart.js - How to push a collection of array into dataset - Stack Overflow

programmeradmin3浏览0评论

I have been trying many ways to push the collection of array into the dataset. Anyone can help me to push an array into stacked chart based on the codepen below?

Here's the example

Codepen stacked bar

Javascript

const getData = ()=>new Array(7).fill('').map(v=>randomScalingFactor());

var barChartData = {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [{
                label: 'Dataset 1',
                backgroundColor: window.chartColors.red,
                data: getData()
            }, {
                label: 'Dataset 2',
                backgroundColor: window.chartColors.blue,
                data: getData()
            }, {
                label: 'Dataset 3',
                backgroundColor: window.chartColors.green,
                data: getData()
            }]

        };
        var ctx = document.getElementById('canvas').getContext('2d');
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: barChartData,
                options: {
                    title: {
                        display: true,
                        text: 'Chart.js Bar Chart - Stacked'
                    },
                    tooltips: {
                        mode: 'index',
                        intersect: false
                    },
                    responsive: true,
                    scales: {
                        xAxes: [{
                            stacked: true,
                        }],
                        yAxes: [{
                            stacked: true
                        }]
                    }
                }
            });

        document.getElementById('randomizeData').addEventListener('click', function() {
            barChartData.datasets.forEach(dataset=>{
                dataset.data = getData();
            });
            window.myBar.update();
        });

Here's the data for arrays

The issues should be the dataset with different colors and total should be the value for Y axis and there should be another collection of array date for X axis and the colors for the dataset should be different. The data for issues and total will be retrieved from Mysql database.

I am using laravel and the table above was achieved using foreach loop.

I have been trying many ways to push the collection of array into the dataset. Anyone can help me to push an array into stacked chart based on the codepen below?

Here's the example

Codepen stacked bar

Javascript

const getData = ()=>new Array(7).fill('').map(v=>randomScalingFactor());

var barChartData = {
            labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July'],
            datasets: [{
                label: 'Dataset 1',
                backgroundColor: window.chartColors.red,
                data: getData()
            }, {
                label: 'Dataset 2',
                backgroundColor: window.chartColors.blue,
                data: getData()
            }, {
                label: 'Dataset 3',
                backgroundColor: window.chartColors.green,
                data: getData()
            }]

        };
        var ctx = document.getElementById('canvas').getContext('2d');
            window.myBar = new Chart(ctx, {
                type: 'bar',
                data: barChartData,
                options: {
                    title: {
                        display: true,
                        text: 'Chart.js Bar Chart - Stacked'
                    },
                    tooltips: {
                        mode: 'index',
                        intersect: false
                    },
                    responsive: true,
                    scales: {
                        xAxes: [{
                            stacked: true,
                        }],
                        yAxes: [{
                            stacked: true
                        }]
                    }
                }
            });

        document.getElementById('randomizeData').addEventListener('click', function() {
            barChartData.datasets.forEach(dataset=>{
                dataset.data = getData();
            });
            window.myBar.update();
        });

Here's the data for arrays

The issues should be the dataset with different colors and total should be the value for Y axis and there should be another collection of array date for X axis and the colors for the dataset should be different. The data for issues and total will be retrieved from Mysql database.

I am using laravel and the table above was achieved using foreach loop.

Share Improve this question asked Dec 19, 2019 at 0:22 Suvin94Suvin94 24010 silver badges32 bronze badges 1
  • Please check I have updated the codepen. And could you please paste here your data array instead of image. – Narendra Jadhav Commented Dec 19, 2019 at 4:03
Add a ment  | 

1 Answer 1

Reset to default 5

You really should provide more information. What have you tried, what failed... Don't expect people do your job, wasting their time so you can nap for an hour. StackOverflow is for specific questions and not for letting others do somebody else's work. And getting data for chart.js is something trivial you can find in any other post about chart.js.

Enough ranting, just letting you know you shouldn't expect answers in the future for questions like that.

  1. The code you posted in your question is quite different to the one from the codepen link, but this can be due to Narendra Jadhav's 'update'. But if confused me enough so I don't know what you want.
  2. You didn't stated if you want to update our data so I didn't implemented updating.
  3. Don't know the use case of this random randomizeData() does, especially with the fixed length of 7. I changed it but as I don't know the reason it may be different to your use case.
  4. I don't know the data format you get from MySQL so I used a possible format. Same as above, could be different to what you want.
  5. Please use an newer version of chart.js and not a year old version. There are no breaking changes, only improvements. Just updating the version eliminated a few bugs, e.g. the strange space between the yAxis and the chart.

Complete code (same as JSBin):

var initialData = [
  {
    'Barcode Sticker Problem':1,
    'Extra':1,
    'Labelling Problem':2,
    'Stock Accuracy':1,
    'Wrong Quality':1
  },{
    'Barcode Sticker Problem':1,
    'Extra':1,
    'Labelling Problem':2,
    'Stock Accuracy':1,
    'Wrong Quality':3
  },
  {
    'Barcode Sticker Problem':2,
    'Extra':2,
    'Labelling Problem':1,
    'Stock Accuracy':2,
    'Wrong Quality':3
  }
]

const colors = [
  'red',
  'blue',
  'green'
]

var barChartData = {
  labels: Object.keys(initialData[0]),
  datasets: []
};

for (var i = 0; i < initialData.length; i++) {
  barChartData.datasets.push(
    {
      label: 'Dataset ' + (i+1),
      backgroundColor: colors[i % colors.length],
      data: Object.values(initialData[i])
    }
  )
}

var barChartOptions = {
  title: {
    display: false,
    text: 'Chart.js Stacked Bar Chart'
  },
  tooltips: {
    mode: 'index',
    intersect: false
  },
  responsive: true,
  scales: {
    xAxes: [{
      stacked: true,
    }],
    yAxes: [{
      stacked: true,
      ticks: {
        precision: 0
      }
    }]
  }
}

var ctx = document.getElementById('canvas').getContext('2d');
window.myBar = new Chart(ctx, {
  type: 'bar',
  data: barChartData,
  options: barChartOptions
});

document.getElementById('randomizeData').addEventListener('click', function() {
  barChartData.datasets.forEach(dataset=>{
    var newData = []
    for (var i = 0; i < dataset.data.length; i++) {
      newData.push(Math.floor(Math.random()*3)+1)
    }
    dataset.data = newData
  });
  window.myBar.update();
});
发布评论

评论列表(0)

  1. 暂无评论