Unable to display numerous bars on the x-axis in vue-chartjs

Having trouble displaying a stacked bar chart with two bars sharing a label on the x-axis. The issue is that the 2nd bar sits below the first one (if you hide the 2021 value, the 2022 bar will appear):

var barChartData = {
  labels: ["January", "February"],
  datasets: [{
    data: [10, 20],
    label: '2021',
    backgroundColor: "#ffe100",
    yAxisId: 'y-stacked',
  }, {
    data: [15, 30],
    label: '2021 Total',
    backgroundColor: "#ee0000",
    yAxisId: 'y-stacked',
  }, {
    data: [6, 19],
    label: '2022 YTD',
    backgroundColor: "#555555",
  }]
};

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: 'label'
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: false,
        ticks: {
          beginAtZero: true,
        }
      }, {
        id: "y-stacked",
        stacked: true,
        display: false,
        ticks: {
          beginAtZero: true,
          min: 0,
        },
        type: 'linear'
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>

<div style="width: 100%">
  <canvas id="canvas"></canvas>
</div>

Any suggestions on getting the 2022 bar to display next to the 2021 bar?

I've attempted adding another x-axis and changing the x-axis stack value to false, but this just unstacks all three bars and places them side by side.

Answer №1

Discovering a useful stacked property within the datasets eliminates the need for multiple axes

var barChartData = {
  labels: ["January", "February"],
  datasets: [{
    data: [10, 20],
    label: '2021',
    backgroundColor: "#ffe100",
    stack: 'stack 1',
  }, {
    data: [15, 30],
    label: '2021 Total',
    backgroundColor: "#ee0000",
    stack: 'stack 1',
  }, {
    data: [6, 19],
    label: '2022 YTD',
    backgroundColor: "#555555",
    stack: 'stack 2',
  }]
};

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: 'label'
    },
    responsive: true,
    scales: {
      xAxes: [{
        stacked: true,
      }],
      yAxes: [{
        stacked: true,
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.bundle.js"></script>

<div style="width: 100%">
  <canvas id="canvas"></canvas>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to remove the old React component when there are two instances of it still active while passing variables?

Recently, I've encountered some unusual behavior with my React component. As a newcomer to React, I have a page where users can configure toast notifications that are displayed. For this functionality, I'm utilizing the react-hot-toast package. U ...

Leveraging Expressjs to act as a proxy for handling cross-origin requests made via AJAX

I'm working on a website that relies entirely on external APIs, without any server-side logic. All data will be retrieved from an external API. The backend server is mainly used for asset management and routing. We've decided to use nodejs with e ...

Monitor changes in Vue 3 global variables

In my codebase, I initially establish a provider in the main.ts file: app.provide('currentPage','test1') Following this setup, I proceed to inject it into a component named Home.vue: inject: ['currentPage'], By doing so, I ...

Properly storing information in the mongoDB

Having trouble saving data in my Angular application correctly. Here is a snippet of my API code: .post('/type/add', function(req, res){ var type = new NewType({ type: req.body.type, subtype: req.body.subtype, }); type.save ...

Customize the serialization of a single object in Newtonsoft.Json

When comparing hashes of serialized objects on the server and client, it is important for the JSON rendering to be identical on both sides. Currently, there is an issue with a number field being serialized differently in JavaScript and .NET - causing the h ...

Unable to integrate npm package into Nuxt.js, encountering issues with [vue-star-rating] plugin

Just starting with nuxt js and running into issues when trying to add npm packages. Below are my attempts. star-raing.js import Vue from 'vue' import StarsRatings from 'vue-star-rating' Vue.use(StarsRatings) nuxt.config.js plugi ...

"Enscroll – revolutionizing the way we scroll in

I recently incorporated the "enscroll" javascript scroll bar into my webpage. You can find more information about it at <div id="enscroll_name"> <ul> <li id="p1">product1</li> <li id="p2">product2</li> ...

Calculate the height of the document in Python by using the function $(document).height()

I am looking to retrieve the height of a document for different URLs, essentially creating a JavaScript function similar to $(document).height() that works across all pages. Any suggestions on how I can accomplish this task? I have experience with Python ...

Tips for resolving the error "Cannot access the title property of undefined" when utilizing NextJS prerendering

I am preparing this page in advance for a specific post within my Next.js application: import Head from 'next/head'; import Link from 'next/link'; import client from '../../lib/apollo/client' import POSTS_WITH_SLUGS from &apos ...

Can someone guide me on how to make an array filled with dates using Javascript?

I am working on developing a Javascript code that can identify all the days leading up to the current date. Here is what I have managed so far: var titleArray = [ "title1", "title2", ]; var pictureArray = today.toString(); var thumbArray = today.toString ...

Receiving an error of "undefined" when trying to capture the selected

One issue I am facing is capturing the selected user option and sending that value in a post request. Let's put aside the post part since it's not directly related to the main question at hand. Currently, the value is showing up as undefined. ...

Struggling to update state in React despite attempts to modify the state

Even though I have set the defaultAccount state to the metamask account, when trying to print it in the code below, it still shows null. The issue arises with fetching the value of defaultAccount. (Please see the error image below) class App extends Compo ...

Importing a .js file into HTML with AJAX

The following JavaScript code is located within index.html between "<script type="text/javascript">" function callanular() { peticion_http = new XMLHttpRequest(); peticion_http.onreadystatechange = showContent; peticion_ht ...

Issue with EnumDeserializer in jackson-mapper 1.9.12 version

I'm currently working on a scenario where I need to map a String to an enum Object using the Jackson ObjectMapper.readValue(String,Class) API. The issue arises when my JSON string contains a Task Object with an Action enum defined as follows: public ...

Virtual machines have encountered issues when attempting to utilize setTimeout within the browser with vm.runInNewContext

When running a JS script using the vm module in a browser, the following details are included: vm.runInNewContext(codeToEval, sandboxObject); Although interval methods like setTimeout and setInterval do not work, even when exposed in the sandboxObject cr ...

Mouseover function not triggering until clicked on in Google Chrome

I'm attempting to execute a function when the cursor hovers over a list item as shown below: <div id="vue-app"> <ul> <li v-for="item in items" @mouseover="removeItem(item)">{{item}}</li> </ul> </div> ...

Having trouble changing the query string in the URL with Angular 4?

My search form includes various filters such as text inputs, checkboxes, and radio buttons. Whenever the user interacts with these filters, the query string in the URL needs to be updated. Consider the following scenario: http://example.com/search?myFilt ...

Is a component updating an unregulated text input to be controlled?

Whenever I attempt to input information into the form and save it in the state, I encounter the following issue: Warning: A component is converting an uncontrolled text input to a controlled one. Input elements should not transition between being contro ...

Is it feasible to alter cookie data within a jQuery ajax call?

I'm currently developing a Chrome extension that enables users to capture all HTTP requests for a specific website, edit components of the request, and then send it again. My plan is to utilize jQuery's ajax function to design and dispatch the a ...

Objects That Are Interconnected in Typescript

I have been delving into TS and Angular. I initially attempted to update my parent component array with an EventEmitter call. However, I later realized that this was unnecessary because my parent array is linked to my component variables (or so I believe, ...