Search code examples
vue.jschart.jsvuejs3vue-chartjs

vue-chartjs horizontal bar chart


I am using Vue-chartjs to create a bar graph in Vue 3:

The bars are vertical. How do I make them horizontal?

<template>
  <Bar
    id="my-chart-id"
    :options="chartOptions"
    :data="chartData"
  />
</template>

<script>
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: 'BarChart',
  components: { Bar },
  data() {
    return {
      chartData: {
        labels: [ 'January', 'February', 'March' ],
        datasets: [ { data: [40, 20, 12] } ]
      },
      chartOptions: {
        responsive: true
      }
    }
  }
}
</script>

Solution

  • Set the indexAxis property.

    <template>
      <Bar
        id="my-chart-id"
        :options="chartOptions"
        :data="chartData"
      />
    </template>
    
    <script>
    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: 'BarChart',
      components: { Bar },
      data() {
        return {
          chartData: {
            labels: [ 'January', 'February', 'March' ],
            datasets: [ { data: [40, 20, 12] } ]
          },
          chartOptions: {
            responsive: true,
            indexAxis: 'y'
          }
        }
      }
    }
    </script>
    

    When using a library, you can check their documentation to find out more.

    Then you would have found the props table;

    enter image description here

    which says:

    "options: The options object that is passed into the Chart.js chart".

    You know that vue-chartjs is a Vue wrapper library for the Chart.js library. Therefore, you go to their documentation. Then you go to the Chart Types part and find your chart type (Bar Chart). If you scroll down a bit you find the options for Bar Charts. The obvious one that stands out to me is the indexAxis - and in fact - it works.

    Demo: here