javascript - 创建堆积预算与实际图表

标签 javascript chart.js

我正在尝试使用 ChartJS 创建一个包含实际金额与预算金额的堆积预算。

所以我的目标是创造这样的东西。

Stacked

我已经做到了这一点。

new Chart(document.getElementById("chartjs-7"), {
  "type": "bar",
  "data": {
    "labels": ["Petrol", "Food", "Kids Clubs", "Alcohol"],
    "datasets": [{
      "label": "Actual Spend",
      "data": [70, 100, 20, 29],
      "borderColor": "rgb(63, 191, 63)",
      "backgroundColor": "rgba(63, 191, 63)"
    }, {
      "label": "Budgeted amount",
      "data": [60, 150, 20, 30],
      "type": "bar",
      "fill": false,
      "borderColor": "rgb(63, 65, 191)",
      "backgroundColor": "rgba(63, 65, 191)"
    }]
  },
  "options": {
    "scales": {
      "yAxes": [{
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

<body>
  <canvas id="chartjs-7" class="chartjs" width="770" height="385" style="display: block; width: 770px; height: 385px;"></canvas>
</body>

但是我的目前看起来像这样。

Stacked2

有什么想法可以做到这一点,或者是否可以使用 graphJS 来实现,我似乎找不到一种方法将它们相互堆叠

最佳答案

您必须将 stacked: true 添加到 xAxes:

"options": {
    "scales": {
      "xAxes": [{
        "stacked": true,
      }],
      "yAxes": [{
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }

演示:

new Chart(document.getElementById("chartjs-7"), {
  "type": "bar",
  "data": {
    "labels": ["Petrol", "Food", "Kids Clubs", "Alcohol"],
    "datasets": [{
      "label": "Actual Spend",
      "data": [70, 100, 20, 29],
      "borderColor": "rgb(63, 191, 63)",
      "backgroundColor": "rgba(63, 191, 63)"
    }, {
      "label": "Budgeted amount",
      "data": [60, 150, 20, 30],
      "type": "bar",
      "fill": false,
      "borderColor": "rgb(63, 65, 191)",
      "backgroundColor": "rgba(63, 65, 191)"
    }]
  },
  "options": {
    "scales": {
      "xAxes": [{
        "stacked": true,
      }],
      "yAxes": [{
        //"stacked": true,
        "ticks": {
          "beginAtZero": true
        }
      }]
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.3.0/Chart.min.js"></script>

<body>
  <canvas id="chartjs-7" class="chartjs" width="770" height="385" style="display: block; width: 770px; height: 385px;"></canvas>
</body>

关于javascript - 创建堆积预算与实际图表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58506016/

相关文章:

javascript - Chart.js 图表从未生成

javascript - (Vue, ChartJS) 从子组件 Canvas 上下文为图表创建渐变背景

javascript - 如何循环或枚举 JavaScript 对象?

javascript - JS 发送带有 django 标签的 html

javascript - JavaScript 中是否可以基于某些父属性名称进行 "dynamic"对象引用?

javascript - 如何在自断言数据 uri 中获取 Azure AD B2C 忘记密码链接

javascript - ChartJS 中的虚线

bar-chart - 在 ChartJs v2 中显示零值条

javascript - Chart.js - 在一页上创建多个图表

javascript - AngularJS Protractor 元素 by.model 找不到元素?