typescriptvue.jsvuejs3vue-chartjs

How to customize the scale for bar charts?


I'm learning to use https://www.npmjs.com/package/vue-chartjs

I'm trying to create a bar chart with y-axis scale ranging from -20 to 70. I'm unable to see the bars in the negative range. I tried using "beginAtZero: false" and even "stacked:true" in the chart options, since there were some suggestions to use stacked property online. But, it didn't help.

Expected behaviour: If the bar level is 20. I want the bar covering -20 to 20. If the bar level is -10, I want the bar covering -20 to -10. The result: If the bar level is 20, bar covers 0 to 20. If the bar level is -10, the bar covers 0 to -10. Screenshot of the output

Below is the code which has the modifications in chart-options. How to achieve the expected behaviour?

 <template>
    <Bar :data="data" :options="options" />
    </template>

<script lang="ts">
import {
  Chart as ChartJS,
  Title,
  Tooltip,
  Legend,
  BarElement,
  CategoryScale,
  LinearScale
} from 'chart.js'
import { Bar } from 'vue-chartjs'

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

export default {
  name: 'App',
  components: {
    Bar
  },
  data() {
    return {
      data: {
        labels: ['January', 'February', 'March'],
        datasets: [{ data: [40, 20, 12] }]
      },
      options: {
        responsive: true,
        scales: {
          y: {
            min: -20, // Set minimum value for y-axis
            max: 70,  // Set maximum value for y-axis
            title: {
              display: true,
              text: 'Values'
            },
            beginAtZero: false,
            ticks: {
              stepSize: 10 // Adjust step size for ticks
            }
          }
        }
      }
    }
  }
}
</script>

Solution

  • scales.y.min tells the chart what should be the minimal value of the Y scale legend (the numbers drawn on the left side of the chart).

    It looks like you want to change the base value of your particular dataset (default is 0):

       datasets: [{ data: [40, 20, 12], base: -20 }]
    

    Note you could also set the chart's options.base to -20 which would change the base value for ALL datasets in current chart.


    See it working.