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

What is the best way to display pages with different states in ExpressJS?

Here is a code block that I have: var express = require('express'); var newsRouter = express.Router(); newsRouter.get('/:news_param', (req, res) => { let news_params = '/haberler/' + req.params.news_param; req.ne ...

Removing undesired entries from a table view using AngularJs

In my table, there is a column called status which could have values like 'Open', 'Closed', 'Verified' and 'Rejected'. I am looking for a way to implement a filter in ng-repeat that will hide the rows with the statu ...

Utilize Set.Attribute prior to entering the for loop

Could someone please clarify why I am unable to declare the var node before the for loop and then simply use appendChild(node) inside the loop? Why is it necessary to declare it for each iteration in order for it to affect all div elements? Otherwise, it w ...

Issue with rendering Backbone subview correctly

Today, I delved into the world of website development using backbone.js. Surprisingly, after a whole morning of trying to crack a puzzling problem, I find myself stuck. Let me focus on the crucial bits of code here. Initially, I have a View named Navigat ...

Error: The variable "Tankvalue" has not been declared

Is there a way to fix the error message I am receiving when trying to display response data in charts? The Tankvalue variable seems to be out of scope, resulting in an "undefined" error. The error message states that Tankvalue is not defined. I need to ...

React/MaterialUI - Is there a way to customize the placeholder text for my multi-input field beyond the provided options?

I have a dropdown menu that accepts two JSON objects, symbol and company. export default function SymbolInput() { const [data, setData] = useState({ companies: [] }); const classes = useStyles(); useEffect(() => { Axios.get(" ...

Angular 6 component experiencing issues with animation functionality

I've implemented a Notification feature using a Notification component that displays notifications at the top of the screen. The goal is to make these notifications fade in and out smoothly. In my NotificationService, there's an array that holds ...

HTML5 video player with secondary playlist

Looking for a videoplayer setup where there are two playlists, but only one can play at a time. When choosing a video from the first list initially, nothing happens. However, after selecting a video from the second list, the first list starts working. HTM ...

Creating an automated sequence of $http requests to sequentially retrieve JSON files with numbered filenames in Angular 1.2

I have a series of JSON files (page1.json, page2.json, etc.) that store the layout details for our website pages. Initially, I would load each page's data as needed and everything was functioning smoothly. However, it is now necessary for all page da ...

Triggering server-side code (node.js) by clicking a button in an HTML page created with Jade

I am currently working on developing a web application and have encountered an issue where I need to execute some server-side code when a button is clicked (using the onClick event handler rather than the Submit button). My tech stack includes Node.js, Exp ...

Utilize ramda.js to pair an identifier key with values from a nested array of objects

I am currently working on a task that involves manipulating an array of nested objects and arrays to calculate a total score for each identifier and store it in a new object. The JSON data I have is structured as follows: { "AllData" : [ { "c ...

Maintain the selected bootstrap tab even after the page is refreshed, even when the content is loaded dynamically

I am currently facing an issue with loading tabs using Angular. Whenever a tab is clicked, the id is saved to localStorage. Now, I want to programmatically click on the same tab using jQuery when the page refreshes. However, since the DOM element for the ...

Choose according to reactjs using react-select

Currently working on a ReactJS app that includes a page with two select elements, where one is dependent on the other. I am integrating react-select and @material-ui. Within the context of dates: [ { "id": 1, "name": "20 ...

If I click on a different VueJS menu, make sure to close the current menu

When using a component menu, each item is displayed independently. However, I would like the open items to close automatically when I click on another item with the menu. I employ a toggle functionality on click to control the opening and closing of the c ...

Is it possible to run my JavaScript script immediately following the execution of npm run build?

Hey everyone! I am trying to run my JavaScript file right after receiving the successful message from npm run build. Currently, I am working on a Vue.js codebase. Is there a way for me to log and create a file in my code repository containing the 'run ...

When NuxtImg is utilized, the image will rotate 90 degrees with Nuxt3 NuxtImg

Recently, I have encountered an issue when using NuxtImg where my images appear rotated by 90°. This problem specifically arises with vertical mobile images that are read from supabase and displayed. Interestingly, the images look fine before uploading th ...

Keying objects based on the values of an array

Given the array: const arr = ['foo', 'bar', 'bax']; I am looking to create an object using the array entries: const obj = { foo: true, bar: true, bax: false, fax: true, // TypeScript should display an error here becau ...

Creating effective test cases for Angular JS controllers

Our team has recently taken on the task of writing test cases for our application, specifically focusing on controllers. Utilizing Mocha, Chai, and Sinon libraries, we are looking for guidance on how to effectively write these test cases. We have shared a ...

Ajax sends the URL location to Python

I'm attempting to piece together some code. There are two distinct functions that I am trying to merge into a single entity. Code snippet: <!DOCTYPE html> <head> <meta http-equiv="content-type" content="text/html;charset=UTF-8"> &l ...

What is the best way to transfer data from Material UI to Formik?

I'm facing an issue when trying to integrate a Material UI 'Select' component into my Formik form. It seems like I am unable to pass the selected values from the Material UI component to Formik's initialValues. const [selectedHours, se ...