Home > Back-end >  stacked bar chart doesn't work - vuechart.js
stacked bar chart doesn't work - vuechart.js

Time:07-21

I try to create a stacked bar chart with vue-chartjs and unfortunately I'm not able to get this job done. My code for the vue-component looks like as follows at the moment:

import { Bar } from 'vue-chartjs'
import { Chart as ChartJS, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js'

ChartJS.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChartStacked',
  components: { Bar },
  props: {
    chartInput: Object,
    chartHeight: Number,
    barColour: String
  },
  data () {
    return {
      chartOptions: {
        responsive: true,
        scales: {
          xAxes: [
            {
              stacked: true
            }
          ],
          yAxes: [
            {
              stacked: true
            }
          ]
        }
      }
    }
  },
  computed: {
    chartData () {
      return {
        labels: this.chartInput.map(d => d.x),
        datasets: [{
          data: this.chartInput.map(d => d.y1),
          backgroundColor: this.barColour
        },
        {
          data: this.chartInput.map(d => d.y2),
          backgroundColor: this.barColour
        }]
      }
    }
  }
}
<template>
  <Bar
    :chart-options= this.chartOptions
    :chart-data="chartData"
    :chart-id="chartId"
    :dataset-id-key="datasetIdKey"
    :plugins="plugins"
    :css-classes="cssClasses"
    :styles="styles"
    :width="width"
    :height= this.chartHeight
  />
</template>

How to define the chart-options properly to get a stacked bar chart? Thanks in advance.

CodePudding user response:

You are using the wrong syntax. You are using the V2 syntax while using V3. Note that in V3, all the scales are their own objects. For more info, please read the migration guide

import {
  Bar
} from 'vue-chartjs'
import {
  Chart,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale
} from 'chart.js'

Chart.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale)

export default {
  name: 'BarChartStacked',
  components: {
    Bar
  },
  props: {
    chartInput: Object,
    chartHeight: Number,
    barColour: String
  },
  data() {
    return {
      chartOptions: {
        responsive: true,
        scales: {
          x: {
            stacked: true
          },
          y: {
            stacked: true
          }
        }
      }
    }
  },
  computed: {
    chartData() {
      return {
        labels: this.chartInput.map(d => d.x),
        datasets: [{
            data: this.chartInput.map(d => d.y1),
            backgroundColor: this.barColour
          },
          {
            data: this.chartInput.map(d => d.y2),
            backgroundColor: this.barColour
          }
        ]
      }
    }
  }
}
  • Related